How to bin IDX based on previous IDX value?

조회 수: 3 (최근 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개)

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

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by