简体   繁体   中英

Matlab: Turning a multiple input anonymous function into a single input

Say that I have an anonymous function with the inputs v and config:

obj_fun = @(v, config) config.dt*(config.e_w*(v(1)^2 + v(2)^2 + config.e_s))*config.m + 2*sqrt((config.G(1)^2 - config.p(1) - config.dt*v(1))^2 + (config.G(2) - config.p(2) -config.dt*v(2))^2)*sqrt(config.e_w*config.e_s)*config.m;

Now, let's say I want I have the values of config and I just an anonymous function in terms of v.

So, I will have:

obj_fun_2 = @(v)...

How can I do that. The main motivation behind this is that I want to use the function, fmincon, but it seems that fmincon only works if your anonymous function has only one input. How can I address this issue? I remember seeing this before. How can I solve this problem.

So, I want something like,

fmincon(obj_fun(..., config),guess, A,B).

where guess is where the algorithm initially starts and A and B are the parameters for the constraints. I just want some variant of this.

如果您有一个带有两个参数的匿名函数obj_fun = @(v, config) ,并且已知一个名为config_value值,则可以通过编写以下命令使用仅第一个值创建一个新的匿名函数:

obj_fun2 = @(v) obj_fun(v, config_value);

I don't know if this is what you want, but here my answer:

for an anonymous function defined as

test = @(a,v) 2*v

You can call it without a like this

test([],3)

However, if you have test = @(a,v) a*v , it won't work.

In the past, I have done the following to use functions with ode45 that required more than the allowed x and t inputs. I do not know that the same approach will work with anonymous functions, but I expect that it will work if you save your function in a new file. I will adapt the method here to your example.

First, save your function in a new file myfunc.m with a top line:

function val = myfunc(v, config);
% your function here, returning "val"

Next, in your calling m-file, wrap your function in a handle that basically disguises it as just a function of v :

h = @(v)myfunc(v, config);  % you might need to put "guess" in place of "v" here

where config is defined in your calling m-file. Finally, pass this handle in place of the function to fmincon :

fmincon(h, guess, A, B);

I do not think you provided everything I need to test this, but as I said I have used this approach in the past to wrap an ODE that is a function of several inputs in such a way that I can pass it to ode45 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM