Search code examples
matlabmatrixindexingmatrix-indexing

How to access n-D matrix with n index vectors?


I have a matrix

A = repmat(1:7,7,1);

I have index vectors

idx1 = [1 3 5];
idx2 = [1 3 5];

I want to access A at the 2d coordinates denoted by idx1(i),idx2(i).

When I do

A(idx1,idx2) = 0;

I get for each element in idx 1, all the elements in idx2 as well. I want only the corresponding elements to be assigned the zero value.

Again: I get

A = 
0 2 0 4 0 6 7
1 2 3 4 5 6 7
0 2 0 4 0 6 7
1 2 3 4 5 6 7
0 2 0 4 0 6 7
1 2 3 4 5 6 7
1 2 3 4 5 6 7

but I want

A = 
0 2 3 4 5 6 7
1 2 3 4 5 6 7
1 2 0 4 5 6 7
1 2 3 4 5 6 7
1 2 3 4 0 6 7
1 2 3 4 5 6 7
1 2 3 4 5 6 7

How to achieve this?

Thanks


Solution

  • The easiest way is probably to use sub2ind to generate the linear indices needed to index into A:

    linear_ind = sub2ind(size(A),idx1,idx2);
    A(linear_ind) = 0;