2012-02-17 81 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)