Matrix addition only to elements equal to zero

4 ビュー (過去 30 日間)
Albin
Albin 2023 年 11 月 20 日
編集済み: Albin 2023 年 11 月 20 日
Hi!
I would like to perform a matrix addition, i.e C=A+B.
However, I want this addition to be performed only for the elements in matrix B that is zero, for all non-zero elements of matrix B the addition should not be performed.
Obviously, this could be done - certainly not beautifully - with an if statement in a loop over all the elements in matrix B. However, I wonder if there is a more neat and faster solution to do this? Especially because my matrices are of size (256,256,329) which makes this solution quite slow.
And for clarity, here is my proposed but unsatisfactory solution:
for i=1:numel(reg_nolower)
if reg_nolower(i) == 0
reg_nolower(i)=reg_nolower(i)+reg_leftarm(i)+reg_rightarm(i);
else
end
end
Thanks in advance!
  2 件のコメント
Bruno Luong
Bruno Luong 2023 年 11 月 20 日
Your code doesn't not reflect your description : your test is on reg_nolower which is the resultant not the reg_leftarm or reg_rightarm, and which is A, B and C in that ?
Albin
Albin 2023 年 11 月 20 日
編集済み: Albin 2023 年 11 月 20 日
Right, sorry. My description was thought of as a general formulation of the problem. Applied on my problem, it would be an addition as D=A+B+C; where reg_nolower is C where the addition shall be performed only if the elements are equal to zero. And A and B are the matrices containing the arms.
I apologize for the confusion.

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

採用された回答

Bruno Luong
Bruno Luong 2023 年 11 月 20 日
C=B;
B0 = B==0;
C(B0)=A(B0);

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by