FeliceM
FeliceM

Reputation: 4199

Replacing specific numbers in matrix

This code generate a matrix n m with alternate 3 and -3

n = 4;
m = 6;
M = zeros(m,n);
M(:,1) = 3*((-1).^(0:m-1).');
for ii = 2:n
    M(:,ii) = (-1)^(ii+1)*M(:,1)
end

Result for n=4 m=6

 3    -3     3    -3
-3     3    -3     3
 3    -3     3    -3
-3     3    -3     3
 3    -3     3    -3
-3     3    -3     3

Now, I am trying to replace the 3 with a 0 and the -3 with a 1 in this way:

M(M==3)  = 0
M(M==-3) = 1

But I do not get what I need because the result is the following:

 0     1     0     0
 1     0     1    -1
 0     1     0     0
 1     0     1    -1
 0     1     0     0
 1     0     1    -1

How can I achieve the replacement of 3 with 0 and -3 with 1?

Upvotes: 2

Views: 59

Answers (1)

Robert Seifert
Robert Seifert

Reputation: 25232

One way:

M = (sign(M) + 1)/2

another one:

M = ~(M - 3)

but your idea is working perfectly for me also, are you sure that you copied it correctly?

M(M== 3) = 0
M(M==-3) = 1

There is no reason, why it shouldn't work. Apart from how you generating it. So maybe there are floating point issues occurring. So to be sure, do at first:

M = round(M)

An alternative way to generate your matrix, without a loop could be:

M = 3*   bsxfun(@(x,y) 2*(~mod(x+y,2)-1/2),(1:m)',1:n)

Upvotes: 2

Related Questions