Trojanian
Trojanian

Reputation: 752

Conditional Replacement of Variables in a Matrix in Matlab

Currently I'm achieving this like so:

b = a;
b(b > 0) = 1;
b(b < 0) = -1;

This works but seems inelegant to me. Surely there is a better way of doing this? A one liner?

Upvotes: 0

Views: 40

Answers (2)

rayryeng
rayryeng

Reputation: 104555

Ander's answer is the one I would go with here. Here's another one as a mental exercise. You can achieve the same using logical operators:

b = (a > 0) - (a < 0);

The elegance of the above expression is such that for any value of a except at 0, only one part of the equation is "on" at any given time. If any value of a is positive, then the output will be logical true as the left side of the equation activates while the right side does not. Similarly, if any value of a is negative, the right side of the equation activates and also evaluates to true while the left side does not. There is a negative sign assigned to the right-hand side and so this coalesces to -1. This in combination with the left-hand side all coalesces to a double precision array thus completes our output. It is also prudent to examine what the expression gives you when any value of a is equal to 0. Since neither of the expressions will activate, this evaluates to logical false for both expressions, and false - false coalesces to 0 which is the result we desire.

Example

>> a = -2:0.5:2

a =

   -2.0000   -1.5000   -1.0000   -0.5000         0    0.5000    1.0000    1.5000    2.0000

>> b = (a > 0) - (a < 0)

b =

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

Upvotes: 2

Ander Biguri
Ander Biguri

Reputation: 35525

b=sign(a); for example?

This should do the same.

Upvotes: 3

Related Questions