Extract only diagonal elements from matrix
이전 댓글 표시
I have a matrix in one variable and a list of coordinates in another variable. Is there a way to extract only the matching pairs of coordinate from the matrix? I.e. X(1),Y(1); X(2), Y(2)...
I can extract all of the permutations (X1, Y1; X1 Y2 ...X2,Y1 ... etc) and then take the diagonal, but I was wondering if there was a simple solution I'm missing to only extract the matched pairs.
Thanks,
Will
%Data
mat = rand(100);
%Coordinates
x_coord = round(rand(10,1)*100);
y_coord = round(rand(10,1)*100);
%Extract coordinates
extracted_coord = diag(mat(x_coord,y_coord));
채택된 답변
추가 답변 (2개)
For a one line solution you can use linear indices via sub2ind:
v = mat(sub2ind(size(mat), 1:length(mat), 1:length(mat));
However i don't know about performance in comparison to the for-loop.
max
2024년 8월 24일
0 개 추천
For a square matrix A, if coordinates are taken from vectors say, xc -> row index and yc -> column index, then all the required elements can be accessed by the single command A((yc-1)*size(A,1)+xc)
Example:
n = 4;
A = round(rand(n)*10)
xc = mod(ceil(rand(1,n)*10),n)+1
yc = mod(ceil(rand(1,n)*10),n)+1
A((yc-1)*size(A,1)+xc)
댓글 수: 1
max
2024년 8월 24일
It works for non square matrix also...
카테고리
도움말 센터 및 File Exchange에서 Mathematics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!