MATLAB: Do some commands run faster or slower in the command line than an M.file

preallocating

Why do some commands run faster and some slower in the command line than in an M.file?
I'm trying to speed up the time it takes my code to run. I looked at the online tutorial and generated a test script using the pre-allocating arrays example from:
If I run the loops with the index of a million (as in the example) it takes to long to run over 30 min; therefore, my test.m file loops are reduced to 100000.
When I run my code I get:
Elapsed time is 29.813208 seconds.
Elapsed time is 0.005239 seconds.
When I execute the same commands from the "command line" I get:
>> clear
>> tic;x = 0;for k = 2:100000;x(k) = x(k-1) + 5;end;toc
Elapsed time is 29.517578 seconds.
>> clear
>> tic;x = zeros(1, 100000);x = 0;for k = 2:100000;x(k) = x(k-1) + 5;end;toc
Elapsed time is 29.077256 seconds.
>>
Notice there is very little difference between in time between the first loop (not pre-allocated) and second loop (pre-allocated). Also it appears that the first loop was a little faster from the command line than from the M file.
M-file code is as follows:{
% Test.m file for checking cpu compute time W/ & w/o preallocating arrays
clear; % clear variables (for testing purposes)
clc; % clears "output" screen
tic %start stopwatch timer
x = 0;
for k = 2:100000
x(k) = x(k-1) + 5;
end;
toc %end stopwatch timer
clear; % clear variables (for testing)
tic %start stopwatch timer
x = zeros(1, 100000); % pre-allocate x
for k = 2:100000
x(k) = x(k-1) + 5;
end
toc %end stopwatch timer
}
System info: Matlab 7.5.0 (R2007b) XP Home (32 bit) on Mac Book Pro (MBP) Intel Core 2 Duo P8600 @ 2.4Ghz 2GB of ram

Best Answer

Look at your preallocated command line example you have:
x = zeros(1, 100000);x = 0;
Remove the x=0 and it will run much faster. Recent versions of MATLAB do some array growth optimization my times are:
>> tic;x = 0;for k = 2:100000;x(k) = x(k-1) + 5;end;toc
Elapsed time is 0.034959 seconds.
>> tic;x = zeros(1, 100000);for k = 2:100000;x(k) = x(k-1) + 5;end;toc
Elapsed time is 0.002369 seconds.