1

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?

carandraug
  • 12,938
  • 1
  • 26
  • 38
user1082072
  • 241
  • 1
  • 6
  • Potentially duplicating [compact-matlab-matrix-indexing-notation](http://stackoverflow.com/questions/792683/compact-matlab-matrix-indexing-notation). There are some slight differences. – Colin T Bowers Nov 29 '12 at 06:10

1 Answers1

2

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

Colin T Bowers
  • 18,106
  • 8
  • 61
  • 89