how can I improve this code???!!!

1 view (last 30 days)
f4r3in on 13 Nov 2019
Edited: Daniel M on 14 Nov 2019
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.)
C_in= 3405;
for i=1:1824
for j=1:10
if temp>d
%this line takes time %from here
%to here
So how can I improve my code ???
f4r3in on 14 Nov 2019
I'm so sorry. this is my project and I cant share it in internet.
but when I click on "run and time" button in MATLAB I understand that these lines take time in my code.
I know you want to help me but for some reasons I cant share it, Sorry.

Sign in to comment.

Accepted Answer

Daniel M
Daniel M on 13 Nov 2019
Edited: Daniel M on 13 Nov 2019
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.
Daniel M
Daniel M on 14 Nov 2019
Edited: Daniel M on 14 Nov 2019
Incremental growth of arrays and dynamic reallocation are tricky things in MATLAB (this is when you cannot know the size that an array will be before the loop occurs). You may be interested in the utility growdata on the File Exchange, where John D'Errico talks about and implements solutions to this problem:

Sign in to comment.

More Answers (0)


Find more on Performance and Memory 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!