有一些限制(进一步来自约翰引用的 Loren 的块):
- 您的代码必须在函数内运行
- 您不能有“数据”的其他别名
“别名”这件事既重要又可能难以正确处理。MATLAB 使用写时复制,这意味着当您调用函数时,您传递的参数不会立即复制,但如果您在函数中对其进行修改,则可能会被复制。例如,考虑
x = rand(100);
y = myfcn(x);
% with myfcn.m containing:
function out = myfcn(in)
in(1) = 3;
out = in * 2;
end
在这种情况下,变量x
被传递给myfcn
. in
MATLAB 具有值语义,因此不得在调用工作区中看到对输入参数的任何修改。因此,第一行myfcn
导致参数in
成为 的副本,x
而不是简单的别名。考虑一下try
/会发生什么catch
- 这可能是一个就地杀手,因为如果您出错,MATLAB 必须能够保留值。在下面的:
% consider this function
function myouterfcn()
x = rand(100);
x = myfcn(x);
end
% with myfcn.m containing
function arg = myfcn( arg )
arg = -arg;
end
然后,应该x
对in进行就地优化myouterfcn
。但以下不能:
% 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
希望这些信息对您有所帮助...