Strange find () behavior

I have this matrix:

a = [1 2 2 1; 1 1 2 2] % 1 2 2 1 % 1 1 2 2 

I want to find all 1 and set them to zero.

 [~, a_i] = find(a == 1); a(a_i) = 0 % 0 2 2 1 % 0 0 2 2 

Why is there still 1 in the first line?

+8
matrix matlab
source share
1 answer

As you do this, you only get the index of column 1 , since you only use the second find output.

 [~, col] = find(a == 1) % 1 1 2 4 

When you use this as an index in a , it will consider them as a linear index and change only 1, 2 and 4 values ​​in a to 0 . Linear indexing is done in column order , so this leads to the output you see.

To do what you are trying to do, you need both outputs from find to get the row and column indexes, and then use sub2ind to convert them to a linear index, which you can then use to index into a .

 [row, col] = find(a == 1); a(sub2ind(size(a), row, col)) = 0; 

It is much easier to use a single output version of find , which simply returns the linear index directly and uses it.

 ind = find(a == 1); a(ind) = 0; 

Or better yet, just use logical indexing

 a(a == 1) = 0; 
+7
source share

All Articles