Hello Matlab community,
I wented to know is there a way to create a code to count how many times a number ouccers in a given matrix.
For example I would like to input:
x=input('Numeber')
=[1 2 3 4 5
1 2 3 5 6
7 2 4 3 5]
Is there a way for Matlab to count how many of each number has occured.
Please provide example Thank you so much.

 채택된 답변

madhan ravi
madhan ravi 2019년 6월 11일
편집: madhan ravi 2019년 6월 11일

0 개 추천

"Is there a way for Matlab to count how many of each number has occured."
The below gives the number of counts of each unique elements in the matrix:
x =[1 2 3 4 5
1 2 3 5 6
7 2 4 3 5]
[uv,~,idx] = unique(x);
n = accumarray(idx(:),1);
% or
n = histc(x(:),uv);
% or
n = sum(x(:).' == uv,2);
Result = [uv,n] % uv - unique elements in the matrix & n - number of times each unique elements appear
Gives:
Result =
1 2
2 3
3 3
4 2
5 3
6 1
7 1
>>

추가 답변 (4개)

Alex Mcaulley
Alex Mcaulley 2019년 6월 11일

1 개 추천

A =[1 2 3 4 5
1 2 3 5 6
7 2 4 3 5];
x=input('Number')
sum(A(:) == x)
Star Strider
Star Strider 2019년 6월 11일

1 개 추천

One way is to use the nnz (link) function with a logical vector:
x = 5
M=[1 2 3 4 5
1 2 3 5 6
7 2 4 3 5]
Count = nnz(M == x)
producing:
Count =
3
Steven Lord
Steven Lord 2019년 6월 11일

1 개 추천

If you want the frequency of one particular element from the matrix, use the techniques madhan ravi, Alex Mcaulley, and Star Strider have given.
If you want just the counts for each unique element, use histcounts.
If you want a picture of the frequency data, use histogram. The graphics object histogram returns also has the bin count information in its properties, but if you don't need the picture I would use histcounts and skip the cost (in time and memory) of creating the picture.

댓글 수: 4

madhan ravi
madhan ravi 2019년 6월 11일
편집: madhan ravi 2019년 6월 11일
Steven but I have shown the way to find the counts for each unique element.
Steven Lord
Steven Lord 2019년 6월 11일
Yes, I see that now. Nice use of implicit expansion, by the way. I still would recommend histcounts or histogram as (among other things) it makes the code author's intent obvious (accumarray and sum are more general than histcounts) and uses the recommended function (in place of histc.)
madhan ravi
madhan ravi 2019년 6월 12일
Very true :)
Rainaire Hansford
Rainaire Hansford 2019년 6월 17일
Thanks Steven when I get the chance I would like to use histogram. But can you show me how am I to use it in a code like the one above.

댓글을 달려면 로그인하십시오.

Rainaire Hansford
Rainaire Hansford 2019년 6월 17일

0 개 추천

You guys are awesome.
I really wanted the first for this project but the rest of youll are great thank you.

카테고리

도움말 센터File Exchange에서 Data Distribution Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by