2012-11-29 77 views
1

我有两个大的矩阵行号和列号以及数据矩阵。我想创建一个矩阵,其中:带两个其他矩阵的索引矩阵

output(i,j) = data(row(i,j),col(i,j)) 

我该如何快速执行此操作?

+0

潜在复制[紧凑MATLAB矩阵转位符号(HTTP ://stackoverflow.com/questions/792683/compact-matlab-matrix-indexing-notation)。有一些细微的差异。 –

回答

2

[T, N] = size(Row),让[DataT, DataN] = size(Data),然后一个单行的解决方案是:

Soln = reshape(Data(sub2ind([DataT DataN], Row(:), Col(:))), T, N); 

这一个班轮看起来有点复杂,所以让我们通过一个例子情况下,步骤打破它一步。我已经包含注释指示与每个部分发生的事情:

%# Set fixed parameters for example matrices 
T = 3; N = 2; 
DataT = 5; DataN = 4; 

%# Generate random Data matrix 
Data = rand(DataT, DataN); 

%# Generate some random subscript index matrices for indexing Data 
Row = randi(DataT, T, N); 
Col = randi(DataN, T, N); 

%# Obtain the linear indices implied by treating Row and Col as subscript matrices 
L = sub2ind([DataT DataN], Row(:), Col(:)); 

%# Use the linear indices to get the data we want 
Soln = Data(L); 

%# Reshape the data from a vector into matrix of size T by N 
Soln = reshape(Soln, T, N); 

为解决此类问题的标准参考是Matrix-Indexing-in-MATLAB