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

MATLABmatrixvector

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)?

Best Answer

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)));