0

I want to get the upper triangle from a matrix. MATLAB have the functions tril and triu, unfortunately they give the wrong triangle. I'm looking for following triangle, is there a command for it or must it be a loop? If so, how does it look?

test=[1 1 1; 1 1 0; 1 0 0];
Mehdi
  • 293
  • 4
  • 13
Orongo
  • 285
  • 1
  • 6
  • 16

1 Answers1

1

You need to do it manually. There are several approaches:

  1. Use flipud to flip vertically before and after applying tril:

    M = magic(3); % example matrix
    result = flipud(tril(flipud(M)));
    
  2. Use bsxfun to create the appropriate mask:

    M = magic(3); % example matrix
    result = M .* (bsxfun(@plus, (1:size(M,1)).', 1:size(M,2)) <= size(M,1)+1);
    

Any of the above gives

>> M
M =
     8     1     6
     3     5     7
     4     9     2
>> result
result =
     8     1     6
     3     5     0
     4     0     0
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147