how do i isolate the elements above both main triangles of a square matrix?

is it better to make the other elements zeroes or to find some kind of returning motive in the indexes?

댓글 수: 2

Depends on the definition of "better"...
Indeterminate as posed.
And the definition of isolate.

댓글을 달려면 로그인하십시오.

답변 (3개)

dpb
dpb 2015년 1월 2일
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??? :)
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

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
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
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.

댓글을 달려면 로그인하십시오.

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;

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2015년 1월 2일

답변:

2015년 1월 2일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by