Reputation: 3616
I have a matrix 100x50. What I want to do is to change the cells having the value > 0 to 0, and the cells having the value=0 to 1. I know its simple, but if anyone could please advise how to do it without loops.
Upvotes: 0
Views: 506
Reputation: 112659
For the general case with negative numbers:
A = A.*(A<0) + (A==0);
Upvotes: 0
Reputation: 2359
sizeMat = size(mat); % Obtain the size of the matrix
final = zeros(sizeMat); % Create a zero full matrix.
idxZero = find(Mat == 0); % Find where = 0;
final(idxZero) = 1; % switch to 1.
Upvotes: 0
Reputation: 8467
Why so complicated?
M = (M == 0);
For this, the zeros have to be exact zeros. If they are only approximately zero, use
M = (abs(M) < eps);
Upvotes: 2
Reputation: 14939
This is a neat way of doing it, using a logical not, if there are only non-negative numbers:
M =
1 2 0 2
2 1 2 2
0 1 2 1
1 0 1 2
M = ~M;
M =
0 0 1 0
0 0 0 0
1 0 0 0
0 1 0 0
If you have negative numbers as well, then:
M =
0 -1 0 3
-3 0 -1 0
0 -2 0 1
1 0 -1 1
M(M >= 0) = ~M(M >= 0)
M =
1 -1 1 0
-3 1 -1 1
1 -2 1 0
0 1 -1 0
Upvotes: 4