MATLAB Answers

Count how many times a number is repeated in a certain row of an array

465 views (last 30 days)
Nathaniel Werner
Nathaniel Werner on 20 Jul 2018
Answered: NSHh on 15 May 2021
Please consider the array
A = [1;1;1;2;2;2;2;2;3;3;4;4;4;4;4;4;4;5;5;5;5];
I would like to determine how many times each number repeats.
For 1, it repeats three times. For 2, it repeats five times, and so on.
If there is other data in columns to the left of the array A that does not follow the same repeating pattern, can I still count how many times each number in a certain column is repeated?
  1 Comment
Adam on 20 Jul 2018
doc histcounts
would be one way of doing it, depending on how many unique values you are likely to have, though however many there are you could use that many bins.

Sign in to comment.

Accepted Answer

Aquatris on 20 Jul 2018
Here is a code;
A = [1;1;1;2;2;2;2;2;3;3;4;4;4;4;4;4;4;5;5;5;5];
c = unique(A); % the unique values in the A (1,2,3,4,5)
for i = 1:length(c)
counts(i,1) = sum(A==c(i)); % number of times each unique value is repeated
% c(1) is repated count(1) times
Aquatris on 5 May 2020
From the above example, the code can be (for relatively newer versions of Matlab;
d = c(counts<4);
where d has the value that appear less than 4 times in the A vector. Alternatively;
I = find(counts<4); % find indices where counts variable elements are less than 4

Sign in to comment.





Community Treasure Hunt

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

Start Hunting!