how do i isolate the elements above both main triangles of a square matrix?
Show older comments
is it better to make the other elements zeroes or to find some kind of returning motive in the indexes?
2 Comments
dpb
on 2 Jan 2015
Depends on the definition of "better"...
Indeterminate as posed.
Image Analyst
on 2 Jan 2015
And the definition of isolate.
Answers (3)
dpb
on 2 Jan 2015
l=logical(ones(size(x))); % a logical array of size of given array (x)
mask=triu(l)&fliplr(triu(fliplr(l)); % mask for those wanted (assume keep diagonal)
ans=x(mask); % as vector
ans=x&mask); % keeping the values only in array
One can simplify above w/ fewer temporaries, etc., but shows one way to skin the cat explicitly.
Golf, anybody??? :)
Image Analyst
on 2 Jan 2015
How about this:
m = magic(4)
upperTriangle = triu(m)
lowerTriangle = tril(m)
In the command window:
m =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
upperTriangle =
16 2 3 13
0 11 10 8
0 0 6 12
0 0 0 1
lowerTriangle =
16 0 0 0
5 11 0 0
9 7 6 0
4 14 15 1
3 Comments
Image Analyst
on 2 Jan 2015
David's "Answer" moved here:
that wasn't my question. imagine that you have a square matrix and you draw the 2 main diagonals. you get 4 triangles right? i need the elements of the upper one. sorry if i wasn't clear enough.
better= easier/shorter
Image Analyst
on 2 Jan 2015
Do you want the diagonals also, like 16, 11, 6, or just the values inside, like 2,10,3. Please use magic(5) as an example and show us the output array or vector that you want as output.
>> magic(5)
ans =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
Image Analyst
on 2 Jan 2015
Check out Mohammad's answer? Does that do what you want? If you don't want the elements exactly underneath the diagonals, then there is an input parameter you can pass in to move the diagonal location up or down.
Roger Stafford
on 2 Jan 2015
Try this:
% Create some arbitrary square matrix, M
n = 12;
M = magic(n);
% Erase all but your "upper triangle"
[I,J] = ndgrid(1:n);
M((I>=J)|(I+J>=n+1)) = 0;
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!