Erick
Erick

Reputation: 144

Select some entries of a matrix given an indexing matrix?

I have two matrices, let's say A and my indexing matrix, I, and where its value is 1, I want to take the value of the matrix A of the same position, and where its value is 0, I want to put a 0 in the position of the matrix A.

For example:

A=

1 2 3

4 5 6

7 8 9

I=

0 1 0

0 0 1

1 1 0

So my desired output would be:

0 2 0

0 0 6

7 8 0

I know I can do it with two for loops, but it's no very efficient. Is there a better way? Any suggestion will be appreciated.

Upvotes: 2

Views: 71

Answers (4)

EBH
EBH

Reputation: 10440

If I is only 1 and 0, just write A.*I:

ans =
     0     2     0
     0     0     6
     7     8     0

If I has some other numbers, then the general case for keeping only the elements in A where I in the same position in k would be:

A = magic(3)
I = [1 2 3
    3 2 1
    2 1 3]
k = 1;
A.*(I==k)

And the output:

A =
     8     1     6
     3     5     7
     4     9     2
I =
     1     2     3
     3     2     1
     2     1     3
ans =
     8     0     0
     0     0     7
     0     9     0

And this, of course, could be altered to I>k or I<=(k+5) or any other logical statement you wish.
The key here is that (I==k) yields a logical output:

ans =
     1     0     0
     0     0     1
     0     1     0

which brings us back to the first case.

Upvotes: 2

Bernhard
Bernhard

Reputation: 3694

You can invert the indexing matrix (this will implicitly convert to binary if it was not binary yet), and set the value at those indices to zero.

 A(~I) = 0

Advantage is that you do not really need to define new or additional matrices, which is expensive if your matrix is large.

Upvotes: 1

edwinksl
edwinksl

Reputation: 7093

I greatly prefer @EBH's answer but here is another way of doing it by using logical:

B = zeros(size(A));
log_I = logical(I);
B(log_I) = A(log_I);
B

B =

     0     2     0
     0     0     6
     7     8     0

Upvotes: 0

Mikhail Genkin
Mikhail Genkin

Reputation: 3460

As pointed out, the best approach in your case is simple term by term multiplication. In a more complicated case, where you have to change the entries according to a rule that depends on your indexing matrix, you can access the entries pointed by your indexing matrix.

For example, if you want to double one-indexed entries and set zero-indexed entries to -1, you should do:

A(I==1)=2*A(I==1);
A(I==0)=-1;

Upvotes: 0

Related Questions