MATLAB: Functions vs scripts: speed

functionsreadabilityscriptsspeed

Dear all,
The structure of my code is the following:
** VERSION A**************
output = fun1(inputs)
Piece of code written directly
in the function
end
************************** **** VERSION B **********
output = fun1(inputs)
% The same piece of code is written
% in a script, that is called by the function
run('script1')
end
Both versions give exactly the same results, but version A is much faster. I think version B is better in terms of code readability (I prefer to break the code in smaller chunks), so I would like to know if someone has an idea why version B is slower
Thanks!!

Best Answer

Glad you're thinking about coding practice and optimization.
Version B is worse in terms of time, debugging, and coding practice. Version B "poofs" in variables into your fun1 local workspace, making it difficult to figure out what went wrong. You also have to use the run function, which is in itself a function that uses the evalin function which is in itself a complex and slow function. Instead of "script1", make it a function by itself.
function output = fun1(inputs)
a = script1(inputs);
output = a+1;
end
The issue with version B:
Say you have 2 scripts:
script1.m contains:
a = 2;
script2.m contains:
for a = 1:10
b = a;
end
function output = fun1(inputs)
run('script1')
run('script2')
output = a; %Which a are you referring to? WHERE did a come from? a = 10. Ooops, forgot script2 uses "a".
end