2012-02-17 94 views
0

我有一個大矩陣,我想用一個調用語句在不同位置檢索一組值。如何索引矩陣中的一組稀疏元素?

因此,舉例來說,我想要檢索(2,3),(6,7)和(15,19)

我知道我可以做以下;

myRows = [2 6 15]; 
myCols = [3 7 19]; 
myTempResults = myBigMatrix(myRows, myCols); % Which will return all possible pairs 
% Then I can do 
% 
myFinalResults = diag(myTempResults); 

但我想知道這樣做的正確/右方式。

由於

+0

[一個matlab矩陣轉換爲向量]的可能重複(http://stackoverflow.com/questions/ 1931545 /轉換-A-MATLAB的矩陣到一個向量) – yuk 2012-02-17 01:58:11

回答

0

你必須使用sub2ind或計算線性指數自己:

a = rand(20,30); % 20 x 30 matrix 
myRows = [2 6 15]; 
myCols = [3 7 19]; 

% method 1, sub2ind 
a(sub2ind(size(a),myRows,myCols)) 

% or calculate it yourself, Matlab is column major 
% and 1-based so row/col (i,j) is (j-1)*nrow+i 
a((myCols-1)*size(a,1) + myRows)