How to get all values existing in arrays/matrices?

조회 수: 66 (최근 30일)
Arif Widianto
Arif Widianto 2020년 3월 24일
편집: Andrei Bobrov 2020년 3월 24일
Hello,
Let say I have a 3-by-2 array with random integer values. For example,
myArray = [98 56; 58 52; 100 56];
What I want to do is, I want to get all value in the array and its frequency and save it to another array like this,
listValue = [98 1; 56 2; 58 1; 52 1; 100 1];
Is there any function or a way to do it?
Thank you in advance.
  댓글 수: 1
Arif Widianto
Arif Widianto 2020년 3월 24일
Thank you for those who tried to answer my question.

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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2020년 3월 24일
편집: Andrei Bobrov 2020년 3월 24일
[a,~,c] = unique(reshape(myArray',[],1),'stable');
out = [a, accumarray(c,1)];
or
out = varfun(@(x)x,array2table(myArray(:)),'GroupingVariables',1);
  댓글 수: 2
Arif Widianto
Arif Widianto 2020년 3월 24일
편집: Arif Widianto 2020년 3월 24일
The first one works for my case. So, if I want it sorted, the only thing I need to do is changing 'stable' to 'sorted' right?
Andrei Bobrov
Andrei Bobrov 2020년 3월 24일
편집: Andrei Bobrov 2020년 3월 24일
Yes or:
[a,~,c] = unique(myArray);
out = [a, accumarray(c,1)];

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

추가 답변 (2개)

KSSV
KSSV 2020년 3월 24일
편집: KSSV 2020년 3월 24일
Read about unique
a = myArray(:) ;
[cnt_unique, unique_a] = hist(a,unique(a)) ;

Walter Roberson
Walter Roberson 2020년 3월 24일
See unique() and accumarray. Or unique and histc or histcounts (but be careful about the last value in histcounts). Or use a loop. Or use sparse(). Lots of ways.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by