1

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}$$

Lemon
  • 12,664

2 Answers2

2

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
2

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.

Daryl
  • 5,598
  • 1
    WHen it says 1:n, does this mean it includes $1 \leq j \leq n$ and not strict inequality? – Lemon Jan 28 '14 at 23:36
  • Yes. For example, the notation 1:5 is equivalent to the array [1,2,3,4,5]. – Daryl Jan 28 '14 at 23:38
  • Never seen this array notation before. Very interesting. In your second code, you are "manually" filling the entries, but in the first one you are filling through columns – Lemon Jan 28 '14 at 23:43
  • @sidht Yes, often there are many different ways to achieve the same result. One I didn't include is the possibility to fill the columns by diagonal using the diag command. – Daryl Jan 29 '14 at 00:19