alternate hist() function

1 次查看(过去 30 天)
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

采纳的回答

Xingda Chen
Xingda Chen 2021-8-6
编辑:Xingda Chen 2021-8-6
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by