# Finding the repetition of each element of a matrix

17 ビュー (過去 30 日間)
AP 2014 年 5 月 21 日

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.

サインインしてコメントする。

### 採用された回答

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 件のコメント表示非表示 1 件の古いコメント
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)

サインインしてコメントする。

### Community Treasure Hunt

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

Start Hunting!