|
"Sean " <sean.dewolski@nospamplease.umit.maine.edu> wrote in message <hsbf9g$7gj$1@fred.mathworks.com>...
> "William " <mr.spammed.a.lot@gmail.com> wrote in message <hsbbuk$84d$1@fred.mathworks.com>...
> > Hi everyone,
> >
> > I've been working on optimizing some code of mine using the Matlab profiler and found that the line using most of the time in my function was the end statement in a for loop. This end accounts for 0.117s, or 13% of the total running time of the function. However, none of the statements within the for loop account for anything more than 0.03s. What is this end doing that takes so long? Has anyone found a solution to this? I'm using R2007a Student version.
> >
> > Thanks very much.
>
> It's *probably* a preallocation issue. Though you didn't post your code so it's kind of hard for us to analyze it.
>
> Are you doing something like this:
> >>for k = 1:100
> >> m(k,:) = some_function_or_expression(k) %Let's say a row is 50 elements long
> >>end
> If so preallocate m:
> >>m = zeros(100,50);
> >>for k = 1:100
> >> m(k,:) = some_function_or_expression(k); %Let's say a row is 50 elements long
> >>end
> and you'll see a huge speedup.
Hi Sean,
I eventually found the error. The problem isn't preallocation, I already do that. My mistake was that I created a variable inside the loop but then used it outside the loop. I thought I had initialized it outside of the loop but forgot to. I guess that Matlab's memory manager had to do something at the end of the loop to allow this variable to be used outside of the loop. The profiler then shows this as the "end;" line taking a lot of time.
|