I have two large matrices of row numbers and column numbers and a matrix of data. I want to create a matrix where:
output(i,j) = data(row(i,j),col(i,j))
How can I do this quickly?
I have two large matrices of row numbers and column numbers and a matrix of data. I want to create a matrix where:
output(i,j) = data(row(i,j),col(i,j))
How can I do this quickly?
Let [T, N] = size(Row)
, and let [DataT, DataN] = size(Data)
, then a one-line solution is:
Soln = reshape(Data(sub2ind([DataT DataN], Row(:), Col(:))), T, N);
This one-liner looks a bit complicated, so let's break it down step by step in an example case. I've included comments to indicate what is happening with each section:
%# 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);
The standard reference for solving these types of problems is Matrix-Indexing-in-MATLAB