Schedule an anonymous function without explicit variable names

I created an anonymous function descriptor as follows:

f = @(x,y)sqr(x)+sqr(y) 

This is a sphere with two variables x and y . It seems to work, as I can name something like

 f(2,3) 

and MATLAB gives me the correct result ans = 13 .

At the last stage, I want to build this function from let from -7 to 7 for both x and y . Therefore i call

 fmesh(f,[-7 7]) 

and the right figure will appear. So far so good.

For some reason, which I don’t want to specify here, now I want to edit the function descriptor:

 f = @(x)sqr(x(1))+sqr(x(2)) 

It should be the same sphere, but this time with two variables x(1) and x(2) . Since the function now wants an array as an argument, I edited the test call

 f([2,3]) 

and this gives me the correct result ans = 13 .

But here's the problem: how do you build a function that wants an array as an argument? The same mesh command, as before, does not work, because [-7,7] has the wrong dimension. The same applies to [[-7 7] [-7 7]] and [[-7 7];[-7 7]] .

How can I get a work schedule from this new function descriptor? Thanks in advance!

+5
source share
1 answer

You cannot get fmesh to pass x and y values ​​as an array, as you expect. What you can do is wrap your anonymous function f in another anonymous function that simply resets the input.

 g = @(x,y)f([x, y]); fmesh(g, [-7 7]) 

A more generalized solution that takes all the inputs and puts them into an array would be

 g = @(varargin)f([varargin{:}]) 
+4
source

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


All Articles