Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior of find()

Tags:

matrix

matlab

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's and put them to zero.

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

%   0     2     2     1 
%   0     0     2     2

Why is there still a 1 in the first row?

like image 948
henry Avatar asked Nov 28 '16 13:11

henry


1 Answers

The way that you are doing it, you are only getting the column index of the 1's since you are only using the second output of find.

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

When you use this as an index into a it's going to treat these as a linear index and change only the 1st, 2nd, and 4th values in a into 0. Linear indexing is performed in column-major order so this results in the output that you are seeing.

To do what you're trying to do, you need both outputs of find to get the row and column indexes and then use sub2ind to convert these 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's a lot easier to use the single output version of find which simply returns the linear index directly and use that.

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

Or better yet, just use logical indexing

a(a == 1) = 0;
like image 170
Suever Avatar answered Oct 15 '22 22:10

Suever