Can Anonymous functions contain unknown variables?

I'm looking at an Anonymous function structured like this:
g = @(x,theta,u,dt)([1,0;0 exp(-dt/theta(5))]*x + [1;theta(3)]*u);
where u and dt are known, but x and theta are not. When I put a break-point before and after this function and check the values of x and theta, they are still undefined, but the code runs. What's going on here?

 Réponse acceptée

It is not an error because you are defining those variables to be positional parameters for the anonymous function you are creating. The values of the known u and dt will be ignored: the named dummy parameters take priority.
At run-time when you call the anonymous function, you will need to provide 4 parameters to the call.
If you want the current values of u and dt to be grabbed and remembered as of the time the anonymous function is created, then do not name them as parameters:
g = @(x,theta)([1,0;0 exp(-dt/theta(5))]*x + [1;theta(3)]*u);
This will create an anonymous function with two arguments x and theta, and will take copies of dt and u as of the time the anonymous function is created and will use those copies when the function is invoked. (Changes to the dt and u variables after that line will not affect the anonymous function because their values have already been copied out.)

Plus de réponses (1)

Star Strider
Star Strider le 16 Août 2016

2 votes

The function itself will not throw an error simply because it exists. Like any other function, you have to call it. That function call could throw an error if all the variables are not defined (whether they’re inherited from your workspace or passed as arguments) and the function is otherwise correctly-written, but the function itself will not.

Catégories

En savoir plus sur Variables dans Centre d'aide et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by