Help on code optimization
显示 更早的评论
I have two matrices A (519840x5) and B (319966x5). Columns 2 to 4 for both contain "day of the year (format: 1-366) ", "hour (format:0-23) " and "minute (format: 0-59)". I would like for each day, hour and minute of matrix B to get a value for the same day, hour and minute, from matrix A and insert it in A, in case they don't have a common day-hour-minute then this value to be -999. I have done using the following code, but since it is too slow i would appreciate any help for speed optimization
for i=1:size(B,1)
id=find(A(:,2)==B(i,2)&A(:,3)==B(i,3)&A(:,4)==B(i,4));
if size(id,1)==1 %check if condition exists
tot=A(id,5); % if yes then get this value
else
tot=-999; %otherwise tot=-999
end
B(i,6)=tot; %insert to last comlum the tot value
end
Thank you
采纳的回答
更多回答(1 个)
bym
2011-12-6
you might start by pre-allocating the new size of B before the for loop:
B = [B,zeros(319955,1)];
for i = 1:length(B)
id=find(A(:,2)==B(i,2)&A(:,3)==B(i,3)&A(:,4)==B(i,4));
if size(id,1)==1 %check if condition exists
tot=A(id,5); % if yes then get this value
else
tot=-999; %otherwise tot=-999
end
B(i,6)=tot; %insert to last comlum the tot value
end
1 个评论
Walter Roberson
2011-12-6
pre-allocating is not really relevant here. If the 6th column does not exist then the first assignment to that column will create the entire column (all rows); in very new versions it might even be able to the extension in-place.
类别
在 帮助中心 和 File Exchange 中查找有关 Convert Image Type 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!