How to replace negative elements in a Matrix with zeros?
古いコメントを表示
A = [2, 3, -1, 5; -1, 4, -7, -3; -6, 0, 3, 9; 7, 6, -3, 8];
B = [9; 17; 15; -3];
AI = inv(A)
I = A*AI
X = AI*B
A*X
Now I am trying to set up a nested for loop to redefine negative elements in A. I need to replace negative elements in A with a zero. How do I go about doing this?
採用された回答
その他の回答 (2 件)
Jan
2018 年 1 月 17 日
Or:
A(A < 0) = 0
3 件のコメント
Jerzy Pela
2020 年 2 月 27 日
編集済み: Jerzy Pela
2020 年 2 月 27 日
I compared both methods, since it was one of the bottlenecks in my calculations and max(A,0) was significantly faster. Keep it in mind if you need to do that calculation numerous times in your script. Otherwise both methods are equal
Josh
2024 年 5 月 4 日
thank you for this extra little insight!
Johnny Zheng
2020 年 10 月 14 日
A = A*(A>0);
This also works!
Have a summary of possible methods:
A = A*(A>0);
A = max(A,0);
A(A<0) = 0;
2 件のコメント
Stephen23
2020 年 10 月 14 日
For non-scalar A (such as that shown in the question) the mtimes operator needs to be replaced with an element-wise times operator otherwise an error or incorrect output is quite likely:
A.*(A>0)
Also note that this method changes -Inf values to NaN, which may be an undesired side-effect:
>> A = [-1,0,1,;-Inf,Inf,NaN];
>> A = A.*(A>0)
A =
0 0 1
NaN Inf NaN
Adam Danz
2020 年 10 月 14 日
You'd need to multiple element-wise,
A = A.*(A>0);
カテゴリ
ヘルプ センター および File Exchange で Variables についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
