Finding the repetition of each element of a matrix

2 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Matt J
Matt J il 21 Mag 2014
Modificato: Matt J il 21 Mag 2014
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 Commenti
Image Analyst
Image Analyst il 21 Mag 2014
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
Matt J il 21 Mag 2014
Modificato: Matt J il 21 Mag 2014
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.

Accedi per commentare.

Più risposte (1)

Image Analyst
Image Analyst il 21 Mag 2014
Try this:
edges = min(A(:)) : max(A(:))
counts = histc(A(:), edges)

Categorie

Scopri di più su Data Distribution Plots in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by