MATLAB: How to change sign of matrix

sign

I have a 5×10 matrix of random values and another 5×10 matrix of +1 and -1 values. I am wanting to apply the sign of the second matrix (+ve or -ve) onto the first matrix. Is there any way to do this?

Best Answer

% Test data:
X = rand(5, 10);
S = 1 - 2 * (rand(5, 10) > 0.5); % Random matrix of 1 and -1
% The calculation:
Result = X .* S
This is a simple multiplication.
An alternative:
X(S == -1) = -X(S == -1)
Related Question