Generating a triangular matrix on MatLab with loops

11.7k Views Asked by At

I am trying to create a triangular matrix from a row vector using loops. I know there are built-in commands that makes this easy, but I am a beginner programmer and I want to test this out.

Here is what I've got so far.

function [ a ] = Up( v )

n = length(v);

a = eye(n);

j = 1;

i = 1;

while(i <= n)

while(j <= n)

a(i,j) = v(i, j);

j = j +1;

end

a(i, i +1) = 0;

i = i + 1;

end

My problem is that it shows me the iterative steps, all I want is the final answer. Also, I can only generate the first row.

For instance, if I give you $v = (3, 8, 9)$, I want to be able to return

$$A = \begin{bmatrix} 3 &8 &9 \\ 0&8 &9 \\ 0&0 &9 \end{bmatrix}$$

2

There are 2 best solutions below

4
On BEST ANSWER

As I said in my comment, you are seeing the output because of the missing semicolon on the line a(i,j) = v(i, j). You also will not get any return value as the variable Upp is not assigned.

Given the way that you are using the loops, it may be preferable to use for loops instead of while loops.

This would result in the following code:

function A = up(v)

n = length(v);         % length of vector

A = zeros(n);          % allocate memory

for j = 1:n            % only loop over all columns
    for i = 1:j        % only the top half
        A(i,j) = v(j); % copy the value from the vector to the matrix
    end
end

You could also rewrite the loop using array notation:

for j = 1:n          % only loop over all columns
    A(1:j,j) = v(j); % copy the value from the vector to the matrix
end

Finally, you could use the repmat and triu commands to create the matrix instead of any loops.

A = repmat(v,n,1); % create a full matrix with each row as the vector
A = triu(A);       % only return the upper triangular portion

Any of these will produce the same result as you are looking for.

0
On

I'm glad that you realize that there are better ways to do this. Having said that, this is the closest I could stay to your original code and and accomplish the said task. I hope you find it helpful.

n = length(v);
Upp = zeros(n);

i = 1;
while(i <= n)
  j = i;
  while(j <= n)
    Upp(i,j) = v(1,j-i+1);
    j = j + 1;
  end
  i = i + 1;
end