Avoid Unnecessary Copies of Data
In this section...
“Passing Values to Functions” on page 29-21
“Why Pass-by-Value Semantics” on page 29-23
“Handle Objects” on page 29-24
Passing Values to Functions
When calling a function with input arguments, MATLAB copies the values from the calling
function’s workspace into the parameter variables in the function being called. However,
MATLAB applies various techniques to avoid making copies of these values when it is not
necessary.
MATLAB does not provide a way to define a reference to a value, as in languages like C+
+. Instead, MATLAB allows multiple output as well as multiple input parameters so that
you know what values are going into a function and what values are coming out of the
function.
Copy-on-Write
If a function does not modify an input argument, MATLAB does not make a copy of the
values contained in the input variable.
For example, suppose that you pass a large array to a function.
A = rand(1e7,1);
B = f1(A);
The function f1 multiplies each element in the input array X by 1.1 and assigns the
result to the variable Y.
function Y = f1(X)
Y = X.*1.1; % X is a shared copy of A
end
Because the function does not modify the input values, the local variable X and the
variable A in the caller's workspace share the data. After f1 executes, the values assigned
to A have not changed. The variable B in the caller's workspace contains the result of the
Avoid Unnecessary Copies of Data