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}$$
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 variableUppis 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:
You could also rewrite the loop using array notation:
Finally, you could use the repmat and triu commands to create the matrix instead of any loops.
Any of these will produce the same result as you are looking for.