我有两个大的行号和列号矩阵以及一个数据矩阵。我想创建一个矩阵,其中:
output(i,j) = data(row(i,j),col(i,j))
我怎样才能快速做到这一点?
让[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