siegel
siegel

Reputation: 829

using matrix elements as indices into another matrix

I have an m by n matrix of 0s called weightmat.

I have an m by k matrix of unique random integers called placeIn, where k < n, and the largest element in placeIn is <= n.

I am trying to place the elements of placeIn into weightmat, using their values as row indices. If a certain row of placeIn has a 4 in it, I want 4 to be placed in the 4th column of the corresponding row of weightmat. Here's example code that does what I'm saying:

% create placeIn

placeIn = [];
for pIx = 1:5
   placeIn = [placeIn; randperm(9,3)];
end

display(placeIn)

weightmat = zeros(5,10);

for pIx = 1:5
   for qIx = 1:3 
       weightmat(pIx,placeIn(pIx,qIx)) = placeIn(pIx,qIx);
   end
end

display(weightmat)

Is there a vectorized way to do this? I would like to accomplish this without the nested for loops.

Upvotes: 0

Views: 74

Answers (1)

Peter
Peter

Reputation: 14937

The trick is sub2ind:

% First generate the row indices used for the indexing.  We'll ignore the column.
[r c] = meshgrid(1:size(placeIn, 2), 1:size(placeIn,1));

weightmat = zeros(5,10);

% Now generate an index for each (c, placeIn) pair, and set the corresponding
% element of weightmat to that value of placeIn
weightmat(sub2ind(size(weightmat), c, placeIn)) = placeIn;

Upvotes: 3

Related Questions