Replacing matrix A with another matrix that counts entries from matrix B
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Azzi Abdelmalek
on 2 Jun 2013
Edited: Azzi Abdelmalek
on 2 Jun 2013
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)
1 Comment
More Answers (2)
Image Analyst
on 2 Jun 2013
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
Alex
on 2 Jun 2013
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!
Image Analyst
on 2 Jun 2013
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
Andrei Bobrov
on 2 Jun 2013
[ii,jj] = ismember(B,A);
out = reshape(accumarray(jj(ii),1),size(A));
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!