how to turn nonzero elements in matrix to 1 in matlab

One way to turn all nonzero elements in a matrix A to 1 in MATLAB is to use element-wise logical operations along with the equality operator. Specifically, you can use the following code snippet:

main.m
A(A~=0) = 1;
13 chars
2 lines

Here, we're first creating a logical matrix A~=0 that has a value of 1 wherever A is nonzero and a value of 0 wherever A is zero. Then we use element-wise indexing to set all elements of A where the logical matrix has a value of 1 to 1.

We can also achieve the same result using a loop and conditional statements, like so:

main.m
for i = 1:size(A,1)
    for j = 1:size(A,2)
        if A(i,j) ~= 0
            A(i,j) = 1;
        end
    end
end
115 chars
8 lines

However, this approach is less efficient and should be avoided if possible.

gistlibby LogSnag