matlab get lower triangular matrix without loop and build in function

2.6k Views Asked by At

I tried to get the lower triangular n x n matrix without using any loop or build in function (except size()). is it even possible? I tried something like this:

a(2:end,1)
a(3:end,2)

Unfortunately, this will work only with fix size matrix. any idea?

4

There are 4 best solutions below

0
On BEST ANSWER

If ones() is allowed:

x = ones(size(a,1),1) *( 1:size(a,2));
y = (1:size(a,1))' * ones(1,size(a,2));
a(y>=x)

If ones() is not allowed:

Ones = a==a;
x = Ones(:,1) *( 1:size(a,2));
y = (1:size(a,1))' * Ones(1,:);
a(y>=x)
0
On

This will zero out all elements that are not part of the lower triangular matrix. If you don't want to alter a, then just make a copy. All you have to do is find where the column index is greater than the row index (and vice verse if you wanted the upper triangular matrix instead).

colinds = repmat( (1:size(a,2)), size(a,1), 1 );
rowinds = repmat( (1:size(a,1))', 1, size(a,2) );
a( rowinds < colinds ) = 0;
1
On

tril(A) returns a lower-triangular matrix from the diagonal and sub-diagonal entries of A.

0
On

Does bsxfun count as a built-in function?

result = a(bsxfun(@ge, (1:size(a,1)).', 1:size(a,2)));