Replace non-zero elements in array with output of a calculation on them

3 ビュー (過去 30 日間)
Hi,
I have an array, A = [2 3 0 7 0 0 9].
How can I replace the non-zero elements of A with thier original value minus one?
I want to generate B = [ 1 2 0 6 0 0 8]
Any help would be appreciated! Thanks,
DB

採用された回答

Walter Roberson
Walter Roberson 2019 年 1 月 16 日
mask = A~=0;
A(mask) = A(mask) - 1;
You can code it as a single expression, but that risks evaluating the comparison twice:
A(A~=0) = A(A~=0) - 1;
  2 件のコメント
dan berkowitz
dan berkowitz 2019 年 1 月 17 日
Thank you! I was actually making the error of evaluating the comparison twice!
DB
Pedapudi Bharath Raja Bhoopal
Pedapudi Bharath Raja Bhoopal 2020 年 10 月 11 日
Thank you

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by