How to merge 2 data sharing 1 variable into a new one without using for-loop?
显示 更早的评论
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 个评论
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
2017-5-15
编辑:Wei Feng Hsu
2017-5-15
采纳的回答
更多回答(1 个)
KSSV
2017-5-15
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 个评论
Wei Feng Hsu
2017-5-15
KSSV
2017-5-15
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
2017-5-15
Guillaume
2017-5-15
"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
2017-5-15
编辑:Wei Feng Hsu
2017-5-15
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!