How to replace every non-0 number with the number in that place added to another number - no loops

1 回表示 (過去 30 日間)
Say I have a matrix I want to loop in a cell in the matrix and change that particular cell to itself added to another number. I have tried to explain mself better with inputs and expected output in the code.
A=[1 0 3;4 5 0;8 0 9] % matrix
B=-7 %additional number
% idk what code i need but every non-zero number in that matrix must be added to b
C=[-6 0 -4; -3 -2 0; 1 0 2] % what I expect the output to be

採用された回答

Stephen23
Stephen23 2020 年 10 月 22 日
編集済み: Stephen23 2020 年 10 月 22 日
I think it is neater to only define the index once:
>> X = A~=0;
>> A(X) = A(X)+B
A =
-6 0 -4
-3 -2 0
1 0 2

その他の回答 (1 件)

Andy
Andy 2020 年 10 月 22 日
A(A~=0) = A(A~=0) + B

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by