Anonymous functions calling in MATLAB

As an experiment (and because I generate anonymous functions from user data), I ran the following MATLAB code:

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 

Basically, I made an anonymous function call. Instead of acting recursively, MATLAB recalled the old definition of a function. However, the workspace does not show it as one of the variables, and the descriptor does not seem to know about it either.

Will the old function be kept behind the scenes while I keep the new? Are there any β€œstrips” with such a design?

+6
source share
1 answer

An anonymous function remembers the corresponding part of the workspace during the definition and creates a copy of it. Thus, if you include a variable in the definition of an anonymous function and later change this variable, it will retain the old value inside the anonymous function.

 >> 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 >> 
+8
source

Source: https://habr.com/ru/post/919061/


All Articles