How to change sign of matrix

29 views (last 30 days)
Fadi Lama
Fadi Lama on 6 Dec 2020
Commented: Jan on 9 Dec 2020
I have a 5x10 matrix of random values and another 5x10 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?

Accepted Answer

Jan
Jan on 6 Dec 2020
Edited: Jan on 6 Dec 2020
% 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)
  2 Comments
Image Analyst
Image Analyst on 6 Dec 2020
Note: This is what I originally thought and posted but deleted it. This does not APPLY the sign of the sign matrix to the other matrix, like my answer does.
For example, if the one matrix is, at some element, say, -10, and the sign matrix there is -1, then the result will be +10. It simply negates the sign, it does not apply the sign. Fadi, take another look at mine. If the sign matrix is negative, my solution will give you negatives in the resulting output matrix, this one will not. Likewise if the sign was positive and the value was negative, this will give a result of negative instead of matching the positive sign value.
This answer works in the special case of all the matrix values being positive only, not where the matrix may have positive and negative values and you want to apply/transfer the sign. However, if you know for a fact that you will never have negative values then this answer is fine.
Jan
Jan on 9 Dec 2020
You are right, Image Analyst. My solution implies, that the original matrix has positive values only. But abs(X).*S cares for negative values also.
@Fadi Lama: You can unaccept my answer and accept Image Analyst's, if he solves the problem.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 6 Dec 2020
Try this:
% Create sample data
M = randi([-5, 5], 5, 10) % Could be + and - values.
signMatrix = 2 * randi([0, 1], 5, 10) - 1
% Apply the sign of the signMatrix to the M matrix
output = abs(M) .* signMatrix

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!