How to merge two different datasets sharing only one variable into a new one without using for-loop?

Hi, I delete the old question because I made too many typos in the old post. I apologize for the error and ambiguity I caused in the last post. Here's what I want to achieve:
Input: 2 dataset
Data 1 has 20 variables and around 40 million observations Data 2 has 22 variables and around 60 million observations
The only variable that both data1 and data2 contained is the one called "secid".
Output: The output should be a subset a data2.
Specifically, I want the observations in Data2 that shared the same "secid" as those in data one
So I first extracted the "secid" variable in data1, and then use for-loop to match them with their counterpart in data2.
And the following is my code:
seicd = unique(data1.secid); %%(using unique cause observations may share the same "secid")
newtable=table; % I want to determine the size here but I can't since it is unknown
warning off %%(Because of the undetermined size of new table)
for i = 1:length(secid)
id1 = (data2.secid==secid(i)); %Search data2 secid that matches the first secid of data1
extracted_secid=data2(id1,:); %Store the matching data into an interim matrix
newtable=[newtable;extracted_secid]; %Store the matching data into the table and move on
end
warning on
And my questions regarded to the for-loop are the following:
1.Since the size of newtable and extracted_secid are undetermined, the speed is slow.
2.I cannot use par-for instead of for since the code
newtable=[newtable;extracted_secid]; is not independent from one loop to another.
3.From my knowledge, for loop should be avoided if there are betters way to do it.
So I am looking for a better way/procedure to achieve my goal with less computational time, since my current one's running time is too long.
Thank you!
Also thanks to KSSV in the last post, but since my typo misguided you. Could you kindly offer the code for my corrected problem? Thanks

 Accepted Answer

u=unique(data1.secid); % those in dataset 1
new=data(ismember(data2.secid,u),:);
should do it providing you don't run into memory issues owing to length of the two tables.
doc ismember % for details
Basically, just table indexing--the ismember call returns logical addressing vector containing 'T' for those rows which match the values in the u array (your unique winnowing down was good) and the second dimension ':' selects all the columns in the table to be included in the new one (presuming, of course, that is what you want, otherwise the second dimension is the list those that are wanted only).

2 Comments

You did catch the misplaced parens, I presume...the first closing ) belongs after the u in the ismember call, of course; the colon is the second array subscript.

Sign in to comment.

More Answers (0)

Tags

Asked:

on 15 May 2017

Commented:

dpb
on 15 May 2017

Community Treasure Hunt

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

Start Hunting!