Shawn
Shawn

Reputation: 333

How do I set all nonzero values in my matrix to 1 in MATLAB?

I have a matrix A, the size of which is 40*20*20 double. The minimum value of matrix A is 0. The maximum value of matrix A is 126. I want to set all nonzero values in matrix A to be "1".I use this following command, but it does not work.

find(A(:,:,:)~= 0) = 1; 

Can anyone tell me why?

Upvotes: 0

Views: 3755

Answers (4)

rayryeng
rayryeng

Reputation: 104464

Do it with logical indexing. Don't use find:

A(A ~= 0) = 1;

However, if it is your desire to replace all values in the matrix with either 0 or 1, where 1 is anything non-zero, you can simply create a logical matrix like so:

A = A ~= 0;

If it is your desire to also have this be a double matrix, you can easily do that by the uplus (unary plus) operator or cast to double1:

A = +(A ~= 0);
%// or
%A = double(A);

1. Credit goes to Rafael Monteiro for originally proposing the casting idea. See his answer here: https://stackoverflow.com/a/32803092/3250829. I also decided to use the uplus operator to be different.

Upvotes: 4

Rafael Monteiro
Rafael Monteiro

Reputation: 4549

If zeros will remain as zeros, and everything else will turn to one, there is no need for indexing nor find. You could do it like this:

A = A ~= 0;

However, it will create a logical matrix. If it has to be double, just cast it to double, like this:

A = double(A ~= 0);

Upvotes: 2

Hashkode
Hashkode

Reputation: 126

As the documentation states (http://de.mathworks.com/help/matlab/ref/find.html), the find function just returns the indices of the elements that satisfy the condition you give as a function paramter to find(). Hence your attempt to assign 1 to the return parameter of find() can not work.

Instead of using the find function, I would advise you to loop through the array contents and check each element individually. In combination with the size function (http://de.mathworks.com/help/matlab/ref/size.html) you can create a size independent function for altering your array. Just store the return values of size() and use them as loop indices.

Upvotes: 1

ewcz
ewcz

Reputation: 13087

find returns the indices, so if you want to access the values, you have to do A(find(A)) = 1;. Note that find finds indices of nonzero values by default: http://ch.mathworks.com/help/matlab/ref/find.html

Upvotes: 0

Related Questions