-3

I want to replace certain values in matrix/vector to -1, but can't seem to be able to.

x = [1 5 6; 2 4 3; 3 4 2; 4 2 1];
z = x(:,1) == 4 % get result I want
z =

 0
 0
 0
 1

changem(z,-1,0) % changem doesn't work

ans =

 1
 1
 1
 1

same if I make array in changem

changem(z,[-1 1],[0 1])
ans =

 1
 1
 1
 1

This also doesn't work

 z(1) = -1
 z =

   1
   0
   0
   1

Why can't I manipulate the vector to get the following values

ans =

 -1
 -1
 -1
 1

This approach works, but an answer to the previous question would be great, thanks.

z = x(:,1) ~= 4; 
z = z * -1; 
z = changem(z,1,0)
ans =

 -1
 -1
 -1
 1
h1vpdata
  • 331
  • 2
  • 15

2 Answers2

1

a logical operation returns values from the binary set {0, 1}. if you want these as {-1, +1} one simple transformation is to multiply by 2, then subtract by one.

z = (x(1, :)  == 4)*2 - 1
  • @crowdedComputeer so the assignment to z is a binary set and only multiplication operation changes the type, and this is why changem or assignment to an index doesn't work. Fascinating. – h1vpdata Dec 26 '15 at 19:21
  • yes. the "==" operation returns logical types that behave differently than numerical types. the transformation I suggested takes advantage of the fact that Matlab is dynamically typed and automatically promotes logicals to doubles when you apply multiplication. – crowdedComputeeer Dec 26 '15 at 19:27
  • @crowdedComputeeer You're confusing dynamic typing and weak typing. The fact that MATLAB allows you to apply `+` on logicals and performs implicit conversions indicates weak typing, but has nothing to do with dynamic typing. For instance, C is statically typed but performs similar implicit type conversions. – jub0bs Dec 26 '15 at 22:49
  • touché @Jubobs, that'll teach me to talk typing off the cuff :-) – crowdedComputeeer Dec 26 '15 at 22:52
0

I have no idea what changeme is, and therefore can't comment on results of that function.

In Matlab and a variety of environments (eg. C, C++), zero evaluates to logical false, and anything besides zero evaluates to a logical true. For example in Matlab, logical(x) will convert a double array x to a binary/logical array. logical(-1) evaluates to 1 (i.e. true). If z is a logical array and you make the assignment:

z(1) = -1;

What happens is the double -1 gets converted to a binary value, which is true (i.e. 1) since everything besides 0 gets converted to true 1. Then 1 is assigned to the first index of z. All is working as it should.

Matthew Gunn
  • 4,451
  • 1
  • 12
  • 30