Finding the repetition of each element of a matrix
조회 수: 2 (최근 30일)
이전 댓글 표시
I have a matrix named A with size N×3. For example,
A = [ 1 2 3;
1 4 5;
5 6 7;
1 3 4;
5 6 7;
1 4 7;
4 3 2;
7 8 9]
In this example, The elements of A are:
B = [1 2 3 4 5 6 7 8 9]
How can I find the repetition of each element of B in A? Actually I am looking for a a vector array like C:
C = [4 2 3 4 3 2 4 1 1]
Here is what I did:
for i=1:numel(B)
C(i) = numel(find(ismember(A, i)==1));
end
I would appreciate it if someone could help me how I can find the repetition of each element of A in a better way and avoid the for-loop.
댓글 수: 0
채택된 답변
Matt J
2014년 5월 21일
편집: Matt J
2014년 5월 21일
Come to think of it, this might be better than what I first proposed (and have now deleted)
C=accumarray(A(:),1);
C=C(B);
Solutions based on HISTC only work if the B(i) are sequential and increment by 1.
댓글 수: 2
Image Analyst
2014년 5월 21일
What is B? I assume it's unique(A).
By the way, the histc() method works on integer lists if they don't increment by 1. I tried it before I posted - changed the 8 to 18. You just get zeros for the counts on the "in-between" missing numbers.
If you have gaps in the integers but don't want gaps in the histogram, you can use B=unique(A:)) and it works just fine:
A = [ 1 2 3;
1 4 5;
5 6 7;
1 3 4;
5 6 7;
1 4 7;
4 3 2;
7 18 9]
B = unique(A)
counts = histc(A(:), B)
You won't have bins with zero counts in them. Just be aware that the bin centers are not sequential. For example (using the above example) bin 7 counts values of 7, bin 8 is for 9, and bin 9 is for 18.
If the numbers aren't integers, that complicates things greatly and the FAQ must be understood: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
Matt J
2014년 5월 21일
편집: Matt J
2014년 5월 21일
What is B? I assume it's unique(A).
I don't know what the OP intended, but conceivably B can be any requested subset of elements in A, and in any order. So, for example if B=[9,1],
>> C=accumarray(A(:),1); C=C(B)
C =
1
3
I guess you could also do
>> C=histc(A(:), 1:max(B)); C=C(B)
C =
1
3
So, fine. There is a histc-based option. I wonder, though, whether accumarray isn't more efficient when B isn't of the form 1:N.
추가 답변 (1개)
Image Analyst
2014년 5월 21일
Try this:
edges = min(A(:)) : max(A(:))
counts = histc(A(:), edges)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Distribution Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!