sachinruk
sachinruk

Reputation: 9869

Extract multiple indices from matrix

I want to access multiple indices of a matrix as shown below. So what I want is indices (1,3),(2,6),(3,7) to be set to one. However, as you can see the entire column is set to one. I can see what it is doing but is there a way to do what I want it to (in an elegant way - no loops).

a=zeros(3,10)
a(1:3,[3 6 7])=1

a =

 0     0     1     0     0     1     1     0     0     0
 0     0     1     0     0     1     1     0     0     0
 0     0     1     0     0     1     1     0     0     0

I realise that you can do something along the lines of

x_idx=1:3, y_idx=[3 6 7];
idx=x_idx*size(a,2)+y_idx;
a(idx)=1;

but just wondering if there was a better, or proper way of doing this in Matlab

Upvotes: 0

Views: 144

Answers (1)

rayryeng
rayryeng

Reputation: 104464

You can use sub2ind, which essentially is doing what you have mentioned in your post, but MATLAB has this built-in:

a = zeros(3,10);
a(sub2ind(size(a), 1:3, [3 6 7])) = 1

a =

     0     0     1     0     0     0     0     0     0     0
     0     0     0     0     0     1     0     0     0     0
     0     0     0     0     0     0     1     0     0     0

Another way would be to create a logical sparse matrix, then use this to index into a:

a = zeros(3,10);
ind = logical(sparse(1:3, [3 6 7], true, size(a,1), size(a,2)));
a(ind) = 1

a =

     0     0     1     0     0     0     0     0     0     0
     0     0     0     0     0     1     0     0     0     0
     0     0     0     0     0     0     1     0     0     0

Upvotes: 3

Related Questions