finding unique cell elements from different size of matrix

3 views (last 30 days)
Hello friends, I have a cell array, but each cell has a different length. For example, a={[1,2] [1,4,2,5] [1,3,4,5,2] [0,5,6] [7,2,4,5] [1,4,2,5,6,8,9]}. Two questions. I want to find elements that are most often repeated in each cell. In this example, the answer is '2'. Note that '2' is not present in cell number 5. The second question, I want to know is how many times answer '2' is repeated. Previous examples deal with uniform cell sizes using the unique function. In this example cell sizes are not constant. Any help, thanks in advance. -DaveG

Answers (1)

Stephen23
Stephen23 on 16 Oct 2018
Edited: Stephen23 on 16 Oct 2018
Your question has nothing to do with unique. The element that occurs the most often in a set of data is called the mode, and it can be obtained using the MATLAB function mode:
>> a = {[1,2],[1,4,2,5],[1,3,4,5,2],[0,5,6],[7,2,4,5],[1,4,2,5,6,8,9]};
>> v = [a{:}]; % convert to numeric vector
>> m = mode(v) % most common element
m = 2
>> n = nnz(m==v) % how many times it occurs
n = 5
  1 Comment
Research
Research on 16 Oct 2018
Thanks a lot. This worked. I could have ever imagined there is a function exist called 'nnz'.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!