Tak
Tak

Reputation: 3616

change the values of a matrix in Matlab

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

Answers (5)

Luis Mendo
Luis Mendo

Reputation: 112659

For the general case with negative numbers:

A = A.*(A<0) + (A==0);

Upvotes: 0

Vuwox
Vuwox

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

A. Donda
A. Donda

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

Stewie Griffin
Stewie Griffin

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

Matt Phillips
Matt Phillips

Reputation: 9691

iiPos = M>0;
iiZeros = M==0;

M(iiPos) = 0;
M(iiZeros) = 1;

Upvotes: 4

Related Questions