How to enumerate an array?

14 vues (au cours des 30 derniers jours)
Aleksandar
Aleksandar le 12 Juin 2015
Commenté : Star Strider le 12 Juin 2015
I want a simple enumeration of the following series a=
['465465465','465465465','465465465','31546895489','31546895489','897897979','897897979', '897897979','897897979','897897979','897897979')'
in order to get
b=(1,1,1,2,2,3,3,3,3,3,3);
I tried with
b(1:length(a))=1;
for i=2:length(a)
if isequal(a(i),a(i-1));
b(i)=b(i-1);
else
b(i)=i+1;
end
end
(but that is not the expected result)

Réponse acceptée

Star Strider
Star Strider le 12 Juin 2015
Create it as a cell array, and use unique. It will give you almost what you want, however unique sorts the results, so they will not be exactly in the order you specified:
a={'465465465','465465465','465465465','31546895489','31546895489','897897979','897897979', '897897979','897897979','897897979','897897979'}';
[as,~,ic] = unique(a);
The ‘as’ vector gives you the sorted results, and ‘ic’ will give the corresponding indices in the order they appear in ‘a’.
  2 commentaires
Konstantinos Sofos
Konstantinos Sofos le 12 Juin 2015
Modifié(e) : Konstantinos Sofos le 12 Juin 2015
I agree with the above solution with a small remark. If you want to have your b vector exactly in the order that you asked you should use
[~,~,b] = unique(a,'stable')
then the result will be
b =
1 1 1 2 2 3 3 3 3 3 3
Star Strider
Star Strider le 12 Juin 2015
Forgot about 'stable'. Thanks!

Connectez-vous pour commenter.

Plus de réponses (1)

Aleksandar
Aleksandar le 12 Juin 2015
Thank you!!
  1 commentaire
Star Strider
Star Strider le 12 Juin 2015
My pleasure!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by