MATLAB Answers

Merging the matched rows of two matrices/files

2 views (last 30 days)
Vijay
Vijay on 30 Sep 2020
Edited: Vijay on 8 Oct 2020
I have two sets of data as in the attached files A and B (where length(A)>length(B)).
I need to
(i) Match:
Match the IDs in column 1 then compare the numbers in column 2 of A and B, and identify the rows with relatively closer numbers in column 2.
For instance B(1,:) -->
3000 70.0800000000000 0
and A(2,:) -->
3000 70.0200000000000 2981.87406731008
(ii) Merge:
Follwing to the match in (i), place the element '0' from column 3 of B in a newly created 4th column in A and leave '.' as the place holders in the remaining rows that doesn't have matching column 2 elements with B
For instance in A(1:2, :) ...
3000 69.9400000000000 2982.16721456415 .
3000 70.0200000000000 2981.87406731008 0
Any help to sort this will be highly appreciated.
Thank you

Accepted Answer

Vijay
Vijay on 8 Oct 2020
Edited: Vijay on 8 Oct 2020
The following loop worked in this case
A(:,4)=100;
for o=1:size(B,1)
for p=1:size(A,1)
if abs(A(p,2)-B(o,2))<=0.05
A(p,4) = B(o,3);
end
end
end
nh1=num2cell(A);
nh1(A == 100) = {'.'};
DT = array2table(nh1);

More Answers (1)

Aman Vyas
Aman Vyas on 6 Oct 2020
Hi,
You can try to use ismembertol which gives or reports members within some tolerance.
You can have a look at this link:
Also you can utilise other ismember syntax as per the functionality you want to achieve for code.
You can refer to this
Hope it helps !
  1 Comment
Vijay
Vijay on 6 Oct 2020
Hi Aman and KSSV,
Thank you so much for your response. I tried the ismembertol function. This function works great but somehow not helpful in my case as it brings more rows in LIA than that in B. The intention is to merge 3rd column elements of B as the 4th column for the matched rows in A.
I did this creating a 4th column in A with a dummy variable and comparing the A-B with a tolerance of 0.05 as shoown in my answer below.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by