Generating a Triangular Matrix via a Vector MATLAB

2.7k Views Asked by At

How do I generate an arbitrary (size n) triangular matrix with a vector?

For example:

A=[1;2;3;4;5;6;7;8;9;10];

And the answer should be:

B=[1,2,3,4; 0,5,6,7; 0,0,8,9; 0,0,0,10]

or

C=[1,2,3,4; 2,5,6,7; 3,6,8,9; 4,7,9,10]

I have already tried hankel, triu and other functions of MATLAB, did not work out.

Thank you in advance.

3

There are 3 best solutions below

1
On BEST ANSWER
n = numel(A)/2-1; % compute size of output matrix 
B = zeros(n); % define B of required size
[ii jj] = ndgrid(1:n); % ii and jj are row and column indices respectively
B(ii>=jj) = A; % fill in values in column-major order
B = B.'; % transpose to get result
2
On

B = triu(ones(4)); B(B==1) = A;

should do the trick.

1
On

I have completed it:

n=4; A=1:n*(2*n+1); B=zeros(2*n) [ii,jj]=ndgrid(1:2*n); B(ii>=jj)=A; B=B.' for i=1:2*n for j=i:2*n B(j,i)=B(i,j); end end B Answer is: B = 1 2 3 4 5 6 7 8 2 9 10 11 12 13 14 15 3 10 16 17 18 19 20 21 4 11 17 22 23 24 25 26 5 12 18 23 27 28 29 30 6 13 19 24 28 31 32 33 7 14 20 25 29 32 34 35 8 15 21 26 30 33 35 36 Thank you so much