MATLAB: How can I improve this code???!!!

improve my code

hi , I write a script and in this script below code take time than other codes in my script.
I need your knowledge to know how can I improve this script. (I know it takes only 0.11 sec to run but in large scale inputs it takes too long and also I want to learn that how can I write a script efficient.)
margin=zeros;
l=1;
C_in= 3405;
for i=1:1824
for j=1:10
temp=COPT(i,3)*COPT_load(j,2);
if temp>d
%this line takes time %from here
margin(l,1)=COPT(i,2)-COPT_load(j,1);
%to here
margin(l,2)=temp;
l=l+1;
end
end
end
So how can I improve my code ???

Best Answer

You should try preallocating margin before the loop. You have only set the value to one element, of zero. Since it's not clear how big margin will be at the end of your loops, you should preallocate it to be the maximum size (1824*10 = 18240). Then at the end, only keep the first 1:l (L) rows using
% after your loops
margin = margin(1:l,:);
Let us know if it's still slow after that, and include a mat file so we can test.