How to bin IDX based on previous IDX value?

3 vues (au cours des 30 derniers jours)
Dc215905
Dc215905 le 7 Oct 2021
Commenté : Dc215905 le 7 Oct 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?

Réponse acceptée

Walter Roberson
Walter Roberson le 7 Oct 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"

Plus de réponses (1)

the cyclist
the cyclist le 7 Oct 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
  1 commentaire
Dc215905
Dc215905 le 7 Oct 2021
Yup, that works too. Thanks!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Function Creation dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by