There are several limitations (in addition to those from the Loren block John quotes):
- Your code should work inside a function
- You must not have other aliases for "data"
Alias ββare important and potentially difficult to understand. MATLAB uses copy-on-write, which means that when you call the function, the argument you pass is not duplicated immediately, but can be copied if you change it inside the function. For example, consider
x = rand(100); y = myfcn(x); % with myfcn.m containing: function out = myfcn(in) in(1) = 3; out = in * 2; end
In this case, the variable x
is passed to myfcn
. MATLAB has semantics of values, so any changes to the input argument in
should not be displayed in the workspace of the call. So, the first line of myfcn
causes the in argument to become a copy of x
, and not just an alias. Consider what happens with try
/ catch
- it could be a killer in place, because MATLAB should keep the values ββif you are mistaken. In the following:
% consider this function function myouterfcn() x = rand(100); x = myfcn(x); end % with myfcn.m containing function arg = myfcn( arg ) arg = -arg; end
then this should get in-place optimization for x
in myouterfcn
. But the following cannot:
% consider this function function myouterfcn() x = rand(100); x = myfcn(x); end % with myfcn.m containing function arg = myfcn( arg ) try arg = -arg; catch E disp( 'Oops.' ); end end
Hope this info helps ...
source share