How to create matrix from descending number of vector elements without loop?

3 views (last 30 days)
Example: I have vector [1 2 5 3 4], and want to create the square matrix [1 2 5 3 4; 1 2 5 3 0; 1 2 5 0 0; 1 2 0 0 0; 1 0 0 0 0], so that the first row has all elements, 2nd row has all but last element, 3rd has all but last 2 elements...all the way to the final row having only the first element.
I am able to do this with a for loop, but can it be done without the loop to save time (actual vector is very large)?

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 21 Jun 2018
Edited: Andrei Bobrov on 21 Jun 2018
A = [1 2 5 3 4];
n = numel(A);
out = ones(n,1)*A.*flip(triu(ones(n)),2);
or just ( MATLAB >= R2016b)
out = A.*rot90(triu(ones(n)));
  2 Comments
Matthew Polatas
Matthew Polatas on 21 Jun 2018
I have a second question: What if I were keeping the last elements instead of the first? For example, [1 2 5 3 4] becomes [1 2 5 3 4; 2 5 3 4 0; 5 3 4 0 0; 3 4 0 0 0; 4 0 0 0 0]?
Thanks, and your previous answer works great.

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 21 Jun 2018
Edited: Stephen23 on 22 Jun 2018
>> V = [1 2 5 3 4];
>> flipud(tril(repmat(V,5,1)))
ans =
1 2 5 3 4
1 2 5 3 0
1 2 5 0 0
1 2 0 0 0
1 0 0 0 0
and
>> hankel([1 2 5 3 4] )
ans =
1 2 5 3 4
2 5 3 4 0
5 3 4 0 0
3 4 0 0 0
4 0 0 0 0

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!