Compare two matrix in matlab

43 views (last 30 days)
MCC
MCC on 15 Jun 2021
Commented: MCC on 15 Jun 2021
I have two matrix data1 and data2. I want to select all rows in data1 that close or equals to data2. I know that loop each element can work but it will take a long time. Is there any easy method I can use?
data1 is attached and data 2 is the following function.
x1 = (0:1:414194)';
data2 = 6*x1;
Thank a lot,
MCC
  1 Comment
SALAH ALRABEEI
SALAH ALRABEEI on 15 Jun 2021
what is the matrices size of data1 and data2!

Sign in to comment.

Accepted Answer

SALAH ALRABEEI
SALAH ALRABEEI on 15 Jun 2021
Here you can extract those element val that are in both data located at index1 and index2
[val,index1,index2] = intersect(data1,data2)
  4 Comments
SALAH ALRABEEI
SALAH ALRABEEI on 15 Jun 2021
Another approach, to find values in a that are close or equal to data in b. Eror 0.001
a=1:10;
b=[3.001,4.99,5,6,10];
[x,y] = meshgrid(a,b);
A = [x(:),y(:)];
index = find(abs(A(:,1)-A(:,2))<1e-3);
x(index) % values in a that are close or equal to data in b
MCC
MCC on 15 Jun 2021
Thanks. This works perfet for my problem.

Sign in to comment.

More Answers (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 15 Jun 2021
Easy and fast efficient solution is Logical Indexing, e.g.:
IND = Data1==Data2
D1 = Data1(IND);
D2 = Data2(IND);
You can also employ round() fcn to reduce the small differences in values of the two data sets.
Or even better to compute the min. differences and get those indices, e.g.:
[minVal,ClosestIND] = min(abs(Data1-Data2))
D1 = Data1(ClosestIND);
D2 = Data2(ClosestIND);
  3 Comments
Sulaymon Eshkabilov
Sulaymon Eshkabilov on 15 Jun 2021
In that case, probably a loop would be an opt.
MCC
MCC on 15 Jun 2021
Edited: MCC on 15 Jun 2021
Yes. Do you have any ideas of how to write this code? The data1 is 47987 by 1 and the data2 is 414195 by 1.
Thanks a lot,
MCC

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!