MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Because the call to the local function, A = fLocal(A), assigns the output to the variable
A, MATLAB does not need to preserve the original value of A during execution of the
function. Within fLocal, the input X has the only copy of the value originally held by A.


Therefore, modifications made to X inside fLocal do not result in a copy of the data. The
assignment, X = X.*1.1, modifies X in place, without allocating a new array for the
result of the multiplication.


function memoryOptimization
A = rand(1e7,1);
A = fLocal(A);
end
function X = fLocal(X)
X = X.*1.1;
end


Eliminating the copy in the local function saves memory and improves execution speed for
large arrays. However, MATLAB cannot apply memory optimization when it is possible to
use the variable after the function throws an error. Therefore, this optimization is not
applied in scripts, on the command line, in calls to eval, or to code inside try/catch
blocks.


Also, MATLAB does not apply memory optimization when the original variable can be
accessed directly during execution of the called function. For example, if fLocal was a
nested function, MATLAB could not apply the optimization because variables can be
shared with the parent function.


Finally, MATLAB does not apply memory optimization when the assigned variable is
declared as global or persistent.


Why Pass-by-Value Semantics


MATLAB uses pass-by-value semantics when passing arguments to functions and
returning values from functions. In some cases, pass-by-value results in copies of the
original values being made in the called function. However, pass-by-value semantics
provides certain advantages.


When calling functions, you know that the input variables are not modified in the caller's
workspace. Therefore, you do not need to make copies of inputs inside a function or at a
call site just to guard against the possibility that these values might be modified. Only the
variables assigned to returned values are modified.


Avoid Unnecessary Copies of Data
Free download pdf