MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
element-wise multiplication. The input is passed by value. However, no copy is made when
calling f1.

The function f2 does modify its local copy of the input variable, causing the local copy to
be unshared with input A. The value of X in the function is now an independent copy of
the input variable A in the caller's workspace. When f2 returns the result to the caller's
workspace, the local variable X is destroyed.

A = rand(1e7,1);
B = f2(A);

function Y = f2(X)
X = X.*1.1; % X is an independent copy of A
Y = X; % Y is a shared copy of X
end

Passing Inputs as MATLAB Expressions

You can use the value returned from a function as an input argument to another function.
For example, use the rand function to create the input for the function f2 directly.

B = f2(rand(1e7,1));

The only variable holding the value returned by rand is the temporary variable X in the
workspace of the function f2. There is no shared or independent copy of these values in
the caller's workspace. Directly passing function outputs saves the time and memory
required to create a copy of the input values in the called function. This approach makes
sense when the input values are not used again.

Assigning In-Place

You can assign the output of a function to the same variable as the input when you do not
need to preserve the original input values.

A = f2(A);

Reassignment to the same variable name follows the copy-on-write behavior described
previously: modifying the input variable values results in a temporary copy of those
values. However, MATLAB can apply memory optimizations under certain conditions.

Consider the following example. The memoryOptimization function creates a large
array of random numbers in the variable A. Then it calls the local function fLocal,
passing A as the input, and assigning the output of the local function to the same variable
name.

29 Memory Usage

Free download pdf