How to merge 2 data sharing 1 variable into a new one without using for-loop?
Show older comments
Hi, I have two data set each with their variables and both of them share 1 variable whose name is "secid". The following is what I want to receive: Extracting all the "secid" from data set 1,and then obtain observations in data set 2 with "secid" extracted from data set 1.
And here is my code to do so:
aaa = unique(data1.secid); %%(using unique cause observations may share the same "secid")
newtable=table;
warning off
for i = 1:length(aaa)
id1 = (data2.secid==aaa(i));
extracteddata=data2(id1,:);
newtable=[newtable;extracteddata];
end
warning on
The running speed is pretty slow, since I create a table without pre-specifying the size of it(But before I receive the result I don't see a way to determine it), and I also use for-loop which I think should be replaced with something better. (I try to use the function "find", but I cannot have multiple input value into it).
Also, I cannot use par-for-loop since the piece of code newtable=[newtable;extracteddata]; is not independent in each loop.
I try to find a more computationally-efficient way since it took like 3 hours to run this for loop cycle (Mainly because data set 1 and data set 2 have millions of observations and around 20 variables)
Thank you!
2 Comments
That line, in the code in your question:
extracteddata(id1,:);
does not do anything (other than slow things down). What was meant by that?
As it is your example does not do much. It simply replicates the same table many times.
Wei Feng Hsu
on 15 May 2017
Edited: Wei Feng Hsu
on 15 May 2017
Accepted Answer
More Answers (1)
KSSV
on 15 May 2017
How about this?
aaa = unique(data1.secid); %%(using unique cause observations may share the same "secid")
newtable=cell(length(aaa),1);
warning off
for i = 1:length(aaa)
id1 = (data2.secid==aaa(i));
newtable{i}=extracteddata(id1,:);
end
warning on
6 Comments
Wei Feng Hsu
on 15 May 2017
KSSV
on 15 May 2017
cell is initialized/ preallocated; so it should be faster. Also I have no idea about the data you have; if clear idea is given, further time can be reduced.
KSSV is correct, preallocation is a good idea:
Wei Feng Hsu
on 15 May 2017
Guillaume
on 15 May 2017
"Basically what I want to receive is to pick out those data in data2 with the variable "secid" that can be found in the "secid" of data1"
and produce what? a new table for each secid? something else? What are you planning to do with that data?
Wei Feng Hsu
on 15 May 2017
Edited: Wei Feng Hsu
on 15 May 2017
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!