Filter löschen
Filter löschen

alternate hist() function

2 Ansichten (letzte 30 Tage)
Xingda Chen
Xingda Chen am 6 Aug. 2021
Bearbeitet: Xingda Chen am 6 Aug. 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

Akzeptierte Antwort

Xingda Chen
Xingda Chen am 6 Aug. 2021
Bearbeitet: Xingda Chen am 6 Aug. 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

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by