How to bin IDX based on previous IDX value?

2 visualizaciones (últimos 30 días)
Dc215905
Dc215905 el 7 de Oct. de 2021
Comentada: Dc215905 el 7 de Oct. de 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?

Respuesta aceptada

Walter Roberson
Walter Roberson el 7 de Oct. de 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"

Más respuestas (1)

the cyclist
the cyclist el 7 de Oct. de 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

Categorías

Más información sobre Function Creation en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by