匿名函数在MATLAB中调用自己

And*_*ica 6 matlab anonymous-function

作为一个实验(因为我正在从用户数据生成匿名函数),我运行了以下MATLAB代码:

h = @(x) x * x
    h = @(x) x * x
h(3)
    ans = 9
h = @(x) h(x) + 1
    h = @(x)h(x)+1
h(3)
    ans = 10
Run Code Online (Sandbox Code Playgroud)

基本上,我自己做了一个匿名函数调用.MATLAB没有采用递归方式,而是记住了旧的函数定义.但是,工作空间不会将其显示为变量之一,并且句柄似乎也不知道它.

只要我保留新功能,旧功能是否会存储在幕后?这种结构有"陷阱"吗?

Jon*_*nas 8

匿名函数在定义时记住工作空间的相关部分,并复制它.因此,如果在匿名函数的定义中包含变量,并在以后更改该变量,则会将旧值保留在匿名函数中.

>> a=1;
>> h=@(x)x+a %# define an anonymous function
h = 
    @(x)x+a
>> h(1)
ans =
     2
>> a=2 %# change the variable
a =
     2
>> h(1)
ans =
     2 %# the anonymous function does not change
>> g = @()length(whos)
g = 
    @()length(whos)
>> g()
ans =
     0 %# the workspace copy of the anonymous function is empty
>> g = @()length(whos)+a
g = 
    @()length(whos)+a
>> g()
ans =
     3 %# now, there is something in the workspace (a is 2)
>> g = @()length(whos)+a*0
g = 
    @()length(whos)+a*0
>> g()
ans =
     1 %# matlab doesn't care whether it is necessary to remember the variable
>> 
Run Code Online (Sandbox Code Playgroud)

  • @AndrewPiliser:我认为写时复制也适用于匿名函数,即只要你不改变`a`的值,你就没事了.**编辑**:刚试过它.是的,这是写时复制. (2认同)