Replacing matrix A with another matrix that counts entries from matrix B
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Azzi Abdelmalek
2013-6-2
编辑:Azzi Abdelmalek
2013-6-2
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 个评论
更多回答(2 个)
Image Analyst
2013-6-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 个评论
Alex
2013-6-2
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
2013-6-2
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!