How to bin IDX based on previous IDX value?

2 Ansichten (letzte 30 Tage)
Dc215905
Dc215905 am 7 Okt. 2021
Kommentiert: Dc215905 am 7 Okt. 2021
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?

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 7 Okt. 2021
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"

Weitere Antworten (1)

the cyclist
the cyclist am 7 Okt. 2021
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

Kategorien

Mehr zu Function Creation finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by