2

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?

xiao li
  • 35

4 Answers4

2

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

Emily
  • 35,688
  • 6
  • 93
  • 141
  • Ha. I can't count the instances I have wasted time writing something the mathworks has already written for me. At least I didn't waste much time with this one. – AnonSubmitter85 Oct 13 '14 at 23:33
0

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)
Steffen
  • 236
0

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

Does bsxfun count as a built-in function?

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