efficient loops.

  • Follow



Hello

I know that the following loops can be vectorized but this
is not the point of my question.

I know (at least) way of saving the calculation of loop in a
list, namely 

--8<------------------------schnipp------------------------->8---
x=1;
z=1;
for k=1:100
  x=x+1;
  z=[z,x];
end
--8<------------------------schnapp------------------------->8---



--8<------------------------schnipp------------------------->8---
x(1)=1;
x=zeros(100,1)
for k=1:100
  x(k+1)=x(k)+1;
end
--8<------------------------schnapp------------------------->8---

Profiler does not tell me what is more efficient (concerning
CPU and memory). 

Can somebody tell me what are the general rules for
minimising computing time and memory? 




Uwe Brauer 
0
Reply oub (83) 2/16/2010 11:15:33 AM

"Uwe Brauer" <oub@mat.ucm.es> wrote in message 
news:878watbfe2.fsf@mat.ucm.es...
>
>
> Hello
>
> I know that the following loops can be vectorized but this
> is not the point of my question.
>
> I know (at least) way of saving the calculation of loop in a
> list, namely
>
> --8<------------------------schnipp------------------------->8---
> x=1;
> z=1;
> for k=1:100
>  x=x+1;
>  z=[z,x];
> end
> --8<------------------------schnapp------------------------->8---

Don't do it this way.  Each iteration through the loop, z changes size which 
means MATLAB needs to allocate new memory for the 1-element-larger z, copy 
all the elements from the old z to the new z, fill in the new element, and 
destroy the old z.  That's very inefficient.  Preallocate, like ...

> --8<------------------------schnipp------------------------->8---
> x(1)=1;
> x=zeros(100,1)
> for k=1:100
>  x(k+1)=x(k)+1;
> end
> --8<------------------------schnapp------------------------->8---

this example (although you'd want to preallocate x to be 101-by-1, as you 
assign a value into x(k+1) when k is 100.)

> Profiler does not tell me what is more efficient (concerning
> CPU and memory).
>
> Can somebody tell me what are the general rules for
> minimising computing time and memory?

Most of the "general rules" are just suggestions, but there's some good 
suggestions in the Programming Fundamentals chapter in the MATLAB user guide 
documentation.  Specifically you should review the last three sections --  
"Performance", "Memory Usage", and "Programming Tips".

Also note that if you copy the first block of code into the Editor, M-Lint 
will flag the line where you update z and suggest preallocating.

-- 
Steve Lord
slord@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ 


0
Reply slord (13267) 2/16/2010 2:56:01 PM


1 Replies
27 Views

(page loaded in 1.677 seconds)


Reply: