필터 지우기
필터 지우기

Keep a tally of the number of occurences of a value in an array

조회 수: 1 (최근 30일)
FredMat
FredMat 2022년 10월 17일
댓글: FredMat 2022년 10월 17일
Hello,
I have an array with integers from 1 to n. I would like to create a second array with the occurence number of the value in the corresponding location (index) of the initial array. For instance, if I have a first array [2 3 1 2 1 4 3 2 4], I want to generate a second array [1 1 1 2 2 1 2 3 2].
I'd like to avoid a series of n conditional statements.
Thx!
  댓글 수: 1
Jiri Hajek
Jiri Hajek 2022년 10월 17일
Hi, you don't need conditional statements, but a loop is probably necessary... You can use logical indexing:
LogicalIndexes = FirstArray == i;
SecondArray(LogicalIndexes) = nnz(LogicalIndexes);

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

채택된 답변

Stephen23
Stephen23 2022년 10월 17일
편집: Stephen23 2022년 10월 17일
A = [2,3,1,2,1,4,3,2,4];
% method 1
F = @(n)nnz(A(1:n)==A(n));
B = arrayfun(F,1:numel(A))
B = 1×9
1 1 1 2 2 1 2 3 2
% method 2
B = sum(triu(A==A.'),1)
B = 1×9
1 1 1 2 2 1 2 3 2
  댓글 수: 1
FredMat
FredMat 2022년 10월 17일
Thanks, method 2 works great. I cannot believe how simple the solution was.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by