rahulk92
rahulk92

Reputation: 85

How do I count the number of occurrences of values in 2 arrays (one is part of the other) in Matlab?

So say I have an array A = [1,2,2,3,4,5,5,5,7]

This is part of another larger array B = [1,2,2,2,2,3,3,3,4,5,5,5,6,7]

What I'd like to do is to count how many times each element appears in A, and divide it by the times it appears in B, and hopefully tabulate the result using the tabulate function.

I'd like my final tabulated result to look as follows

Element - Occurrence - %age of occurrence
1   -   1    -    100%
2   -   2    -    50%   
3   -   1    -    33.3%
4   -   1    -    100%
5   -   3    -    100%
6   -   0    -    0%
7   -   1    -    100%

I believe this would involve a for loop where I create a new array C such that it identifies which elements in A appear in B and each time it does add 1 to its respective value, and if it doesn't exist in B, return 0. I don't know how to proceed though and some direction would be greatly appreciated!

Upvotes: 3

Views: 82

Answers (1)

mikkola
mikkola

Reputation: 3476

This is a good use case for hist, which is usually quite fast. You can bin the data in A to histogram bins ranging from min(A) to max(A), and apply the same bins to allocate the data in B. Then you can get your percentage values by simply dividing the numbers of occurrences in both arrays.

For example:

[nA, uA] = hist(A, min(A):max(A));
nB = hist(B, uA);
result = 100*(nA./nB)'

Edit: the numbers of occurrences of elements of A is given by nA.

Upvotes: 4

Related Questions