How to extract the upper diagonal part of a matrix into a 1 dimensional vector ?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Tuong Nguyen Minh
am 6 Jun. 2020
Beantwortet: Image Analyst
am 6 Jun. 2020
Dear Matlab user community
I have a K by K matrix like this for example when K = 3
A =
1 2 3
4 5 6
7 8 9
A =
1 2 3
4 5 0
7 8 9
A =
1 0 3
4 5 0
7 8 9
I would like to extract the value of [2 3 6] , [2 3 0] and [0 3 0] in this order .
My attemp was terribly inefficient
function result = flat_alpha(A)
K = size(A,1);
result = [];
for ii = 1:K
for jj = 1:K
if ii<jj
result = [result A(ii,jj)];
end
end
end
end
Could you kindly help me solve this problem ?
Thank you very much for your enthusiasm !
0 Kommentare
Akzeptierte Antwort
David Hill
am 6 Jun. 2020
If A will always be a 3x3, then
B=A([4 7 8]);
3 Kommentare
David Hill
am 6 Jun. 2020
If the order does not matter:
B=[];
for k=1:length(A)-1
B=[B,diag(A,k)'];
end
David Hill
am 6 Jun. 2020
Same order as you specified
B=[];
for k=1:length(A)-1
B=[B,A(k,k+1:end)];
end
Weitere Antworten (1)
Image Analyst
am 6 Jun. 2020
Try triu():
% Set up
K = 3;
A = reshape(1:K^2, K, K)'
% Solution:
upperTriangle = triu(A, 1)
oneDVector = upperTriangle(upperTriangle~=0)
You get [2;3;6] as requested.
I'm not sure what your rules are for getting the second and third version of your A matrix.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Linear Algebra finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!