How to bin IDX based on previous IDX value?

2 ビュー (過去 30 日間)
Dc215905
Dc215905 2021 年 10 月 7 日
コメント済み: Dc215905 2021 年 10 月 7 日
Hello,
I have an array:
a = [0 0 1 2 2 1 2 2 1 0 1 0 2];
I would like to bin the IDX of 2 into three different variables.
1) B = IDX of 2 if the preceding IDX == 1
2) C = IDX of 2 if the preceding IDX == 0
3) D = IDX of 2 if the preceding IDX == 2
Any suggestions?

採用された回答

Walter Roberson
Walter Roberson 2021 年 10 月 7 日
a = [0 0 1 2 2 1 2 2 1 0 1 0 2];
temp = [-1 a];
idx2 = temp(2:end) == 2;
b_loc = idx2 & temp(1:end-1) == 1;
c_loc = idx2 & temp(1:end-1) == 0;
d_loc = idx2 & temp(1:end-1) == 2;
new_a = string(a);
new_a(b_loc) = "B";
new_a(c_loc) = "C";
new_a(d_loc) = "D";
new_a
new_a = 1×13 string array
"0" "0" "1" "B" "D" "1" "B" "D" "1" "0" "1" "0" "C"
  1 件のコメント
Dc215905
Dc215905 2021 年 10 月 7 日
Thank you!

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

その他の回答 (1 件)

the cyclist
the cyclist 2021 年 10 月 7 日
Is this what you mean?
a = [0 0 1 2 2 1 2 2 1 0 1 0 2];
loc2 = a(2:end)==2;
pre = a(1:end-1);
b = 1 + find(loc2 & (pre==1))
b = 1×2
4 7
c = 1 + find(loc2 & (pre==0))
c = 13
d = 1 + find(loc2 & (pre==2))
d = 1×2
5 8
  1 件のコメント
Dc215905
Dc215905 2021 年 10 月 7 日
Yup, that works too. Thanks!

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by