我正在尝试根据用户输入参数输入MATLAB中的符号函数,然后使用fminsearch(Fun,x0)最小化该函数,这似乎只允许符号函数。我似乎找不到一种基于Sym2Poly()以外的用户输入来生成任意符号函数的方法,这仅在我想生成多项式函数时起作用。有什么想法吗?
我认为 str2func
就是您要寻找的:
% this is actually your user input, it could be taken,
% for example, using inputdlg function
user_in = inputdlg('Enter your function:','Function'); % '2*x + 4'
% the user input is transformed into a function handle
% that can be passed to fminsearch
fh = str2func(['@(x) ' user_in]);
% the function created from the user input is evaluated
x = fminsearch(fh,x0);
您也可以让用过的定义输入参数(但我认为fminsearch
这是必需的):
str = '@(x,y) 2*x + 4*y + 1';
fh = str2func(str);
有关更多信息:
- 官方文件
- 不错的教程