How to change sign of matrix
8 ビュー (過去 30 日間)
古いコメントを表示
採用された回答
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
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
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
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!