Replacing matrix A with another matrix that counts entries from matrix B

Sorry for the confusing title and I will explain everything below.
I would like something that does the following (better if loops are not used): A code that replaces the entire matrix A (size unknown but all entries are unique integers) by counting the number of same entries as A has from matrix B (size unknown, all integers, might have redundant entries).
Example.
Input is A = [1 3 5; 6 4 11]; B = [3 3 2 1 4 6 10 29; 4 2 1 1 99 1 7 29; 8 2 1 6 7 6 11 1]
After using the code to replace A, the output should be A = [6 2 0; 3 2 1]; (since there are 6 of number 1, 2 of number 3, no number 5, 3 of number 6, 2 of number 4 and only one of number 11).
Thanks very much for your help. Please let me know if you have any questions.

 Accepted Answer

A = [1 3 5; 6 4 11];
B = [3 3 2 1 4 6 10 29; 4 2 1 1 99 1 7 29; 8 2 1 6 7 6 11 1]
A=arrayfun(@(x) sum(sum(ismember(B,x))),A)

More Answers (2)

I hope this isn't your homework or you can't turn this in:
% Sample data:
A = int32([1 3 5; 6 4 11])
B = int32([3 3 2 1 4 6 10 29; 4 2 1 1 99 1 7 29; 8 2 1 6 7 6 11 1])
% Now get the histogram.
edges = unique(A(:))
counts = histc(B(:), edges)
In the command window:
A =
1 3 5
6 4 11
B =
3 3 2 1 4 6 10 29
4 2 1 1 99 1 7 29
8 2 1 6 7 6 11 1
edges =
1
3
4
5
6
11
counts =
9
2
2
0
7
1

4 Comments

It's not homework. I'm writing a function for predicting winning chances for Texas Hold Them poker game for fun. I'm planning on doing a GUI for the function on post it on the forum.
Thanks very much
And, how come that number 1 from matrix B has 9 counts? There are only 6 of number 1 in matrix B I thought.
Dear predecessors, I am a beginner to matlab. Recently i am studying a thesis about my major, in which matlab is used. Something goes wrong while repeat the process of the thesis and i can't find a solution or help from my friends. Would you kindly take a few mins to have a look my question and give me some sugguestion? This is my question: http://www.mathworks.com/matlabcentral/answers/77715-how-to-find-the-polynomial-coefficients-of-two-array
Many thinks!
Sorry - forgot to eliminate the elements in B that weren't in A so the 2's got counted. Try this code:
% Sample data:
A = int32([1 3 5; 6 4 11])
B = int32([3 3 2 1 4 6 10 29; 4 2 1 1 99 1 7 29; 8 2 1 6 7 6 11 1])
% Eliminate elements of B that aren't in A.
inA = ismember(B(:), A(:))
B = B(inA);
% Now get the histogram.
edges = unique(A(:))
counts = histc(B(:), edges)
Results:
counts =
6
2
2
0
3
1

Sign in to comment.

Categories

Tags

Community Treasure Hunt

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

Start Hunting!