alternate hist() function

1 vue (au cours des 30 derniers jours)
Xingda Chen
Xingda Chen le 6 Août 2021
Modifié(e) : Xingda Chen le 6 Août 2021
I wanted to know how many times a number is repeated in a vector, so I used the hist() function.
For example, an extracted idea of my code runs like this
a = [1 1 2 3 4];
b=unique(a); %b=[1 2 3 4]
c=hist(a,b); %c=[2 1 1 1]
d=find(c~=0); %d=[1 2 3 4] %this can be finding with any condition, regarding the repetitition times
result=a(d); %result=[1 1 2 3] %find the values inside variable a, mathcing the condidiotn above
Looking at b and result variables, I know there are two 1s, and one of 2,3,4 each. I used this way to code the rest
but here is the problem that cost an exception, and I don't know how to get around it, another example that makes an error
a = [4 4];
b=unique(a); %b=[4]
c=hist(a,b); %c=[0 0 2 0] % here i expect the vector to be the length of b like above (1 in this case), but it gives me length of 3
d=find(c~=0); %d=2 %this can be finding with any condition, regarding the repetitition times
result=a(d); % error, index exceeding array element
I itentified where the problem is: looks like c=hist(a,b) will output a result with length(c)= length(b)-- if b is a vector with 1+ elements, if b is a scalar then length(c)=b.
This is throwing error in my larger module, and I am not sure how to get around that.
Any smart ideas?
Thanks

Réponse acceptée

Xingda Chen
Xingda Chen le 6 Août 2021
Modifié(e) : Xingda Chen le 6 Août 2021
a = [4 4];
b=unique(a);
c=hist(a,b);
c=nonzeros(c);
d=find(c~=0);
result=a(d);
I got a simple solution. Closing the question.
PS, Helps a lot to clearly type the problem out. Didn't know what to do before I post this

Plus de réponses (0)

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by