parson
parson

Reputation: 23

Matlab Matrix indexing with both column and row

Suppose I have a 2 by 5 matrix:

d1=  3     3     1     1     2
     4     4     2     3     4

and there is a 4 by 5 zero matrix :

z1=  0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0

Each column of d1 shows the positions of 1's in the corresponding column in z1. Specifically, I want to get a result like:

r1=  0     0     1     1     0
     0     0     1     0     1
     1     1     0     1     0
     1     1     0     0     1

I am looking for an efficient way to obtain r1 from d1 and z1.

Upvotes: 0

Views: 97

Answers (1)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

Convert d1 to linear indices, and use them to index z1:

% Prior to R2016b:
I = bsxfun(@plus, d1, (0:size(d1,2)-1) * size(z1,1));

% On or after R2016b:
I = d1 + (0:size(d1,2)-1) * size(z1,1));

% Index using the linearized indices
z1(I) = 1

Upvotes: 3

Related Questions