Find Function in MATLAB to Compare two vectors
13 次查看(过去 30 天)
显示 更早的评论
Hi All,
Hope everyone is doing great. I have a situation that I am trying to figure out. I have two matrices, that I would like to compare their elements of. Lets call matrix A & B. I would like to match all the elements of 1st column A to the elements of 1st column of B and returns the elements from 2nd column of B.
Currently, I am using Find function, but seems like Find fuction returns no value, if position of the elements are different. What I would like is the matching of columns regardless of the position of elements. In other words, if "5" occurs at 5th Row on A and at 9th row of B, I would like MATLAB to show me the match.
One way I could think, is to run a loop individually for each element of A to use Find function in column B. But, I think it would be very inefficient and I was hoping someone could guide me for a better code.
Looking forward to hear from you guys. Thank you for your time.
2 个评论
Matt Fig
2012-9-5
编辑:Matt Fig
2012-9-5
Your explanation is confusing. What do you mean, "and returns the elements from 2nd column of B."
Are you only comparing first columns? What are the array sizes? What is this about the second column of B?
It is always easiest to just give two small example arrays as your inputs and show what you want as the output...
回答(2 个)
Image Analyst
2012-9-5
Might not be as slow as you think. How large are your arrays? I did this for 10,000 rows in about .6 seconds.
clc;
format compact;
format shortg;
numberOfRows = 10000;
a = randi(9, [numberOfRows,2])
b = randi(9, [numberOfRows,2])
tic;
% Get all unique values in the first column of a.
uniqueAValues = unique(a(:,1))
for k = 1:length(uniqueAValues)
matchingRows = find(b(:,1) == uniqueAValues(k));
% Print them out
for r = 1:length(matchingRows)
fprintf('%d occurs in b at row %d. b in the second column = %d\n',...
uniqueAValues(k), matchingRows(r), b(r, 2));
end
end
toc
0 个评论
Matt Fig
2012-9-5
编辑:Matt Fig
2012-9-5
Given your example inputs and outputs:
% The inputs
A = [1, 2, 3, 4, 5].'
B = [2, 4, 5, 6, 7;10, 11, 13, 14, 15].'
% Get the outputs
C = nan(size(A,1),1);
for ii = 1:size(A,1)
I = B(A(ii)==B(:,1),2);
if ~isempty(I)
C(ii) = I(1);
end
end
Are the values in the real first column of B unique? Is B meant to be a lookup table?? If so, then there is a simpler method.
If B is meant to be a lookup table, then use:
C = nan(size(A(:,1)));
idx = ismember(A(:,1),B(:,1));
C(idx) = interp1(B(:,1),B(:,2),A(idx,1));
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!