How to change sign of matrix

8 ビュー (過去 30 日間)
Fadi Lama
Fadi Lama 2020 年 12 月 6 日
コメント済み: Jan 2020 年 12 月 9 日
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?

採用された回答

Jan
Jan 2020 年 12 月 6 日
編集済み: Jan 2020 年 12 月 6 日
% 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 件のコメント
Image Analyst
Image Analyst 2020 年 12 月 6 日
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 2020 年 12 月 9 日
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.

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2020 年 12 月 6 日
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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by