Subtracting vector elements, with an if condition?

11 ビュー (過去 30 日間)
Sanshu Bhutiani
Sanshu Bhutiani 2018 年 5 月 10 日
コメント済み: Sanshu Bhutiani 2018 年 5 月 10 日
Hey guys,
I need to subtract every element in my array with the element next to it and before it, then if the result of the subtraction is 0 on either subtraction, I need a new array where the elements which weren't 0 are keep their original values, but the elements which were 0 stay 0. Is this possible?
a=[1 2 3 4 5 6 7 7 7 7 7 8 9 10 11 12 13];
b=[1 2 3 4 5 6 0 0 0 0 0 8 9 10 11 12 13];
Thanks in advance!

採用された回答

Stephen23
Stephen23 2018 年 5 月 10 日
編集済み: Stephen23 2018 年 5 月 10 日
a = [1 2 3 4 5 6 7 7 7 7 7 8 9 10 11 12 13];
b = a;
d = diff(a)==0;
b([false,d] | [d,false]) = 0
  1 件のコメント
Sanshu Bhutiani
Sanshu Bhutiani 2018 年 5 月 10 日
This works really well! Thank you!

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

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2018 年 5 月 10 日
b = a;
mask = b(1:end-1) = b(2:end);
b([false,mask]|[mask|false]) = 0;

Sanshu Bhutiani
Sanshu Bhutiani 2018 年 5 月 10 日
Thanks everybody for the answers, it's really appreciated :).

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by