Matlab:如何将多变量符号表达式转换为fminsearch可以使用的函数? [英] Matlab: How do I convert multivariable symbolic expression to a function that fminsearch can use?
问题描述
我有一个多变量符号表达式,
I have a multivariable symbolic expression say
c = x^2 +y^2 + z^2
使用matlabFunction(c)返回
using matlabFunction(c) returns
ans = @(x,y,z)x.^2+y.^2+z.^2
我无法将此输入到fminsearch中(因为它有多个标量输入正确吗?).我该如何更改输出的格式,以便它使用fminsearch实际允许的内容,例如
I can't input this into fminsearch (because it has multiple scalar inputs right?). How can I change the format of the output so it takes something that fminsearch actually allows, something like
@(x)x(1)^2+x(2)^2+x(3)^2
手动为3个变量而不是数百个变量执行此操作是可行的.
It is feasible to do this manually for 3 variables but not for hundreds.
如果有帮助,这些错误看起来就像:
The errors look something like if it helps:
Error using symengine?makeFhandle/@(......) Not enough input arguments.
Error in fminsearch (line 190) fv(:,1) = funfcn(x,varargin{:}):
推荐答案
想到的一个快速变通办法是创建另一个匿名函数作为中间步骤:
A quick workaround that comes to mind is to create another anonymous function as a go-between:
fun = @(x,y,z)x.^2+y.^2+z.^2;
funMiddleMan = @(x) fun(x(1),x(2),x(3));
对于大量参数,解决方案变得更加复杂.
我的第一个直觉是按以下方式使用 str2func
>
For a large number of arguments, the solution becomes a little more complicated.
My first instinct is to use str2func
in the following manner
nVar = 3;
funMiddleMan = str2func(['@(x)fun(',sprintf('x(%d),',1:nVar-1),'x(',num2str(nVar),'))']);
但是,此无效,因为str2func
无法(当前)将fun
的定义嵌入到与funMiddleMan
相连的本地工作空间中;表示以这种方式调用funMiddleMan
将生成"Undefined function 'fun'
"错误.可以通过使用 eval
:
However, this will not work since str2func
cannot (currently) embed the definition of fun
within a local workspace attached to funMiddleMan
; meaning that calling funMiddleMan
in this manner will generate an "Undefined function 'fun'
" error. The problem can be circumvented by using eval
:
funMiddleMan = eval(['@(x)fun(',sprintf('x(%d),',1:nVar-1),'x(',num2str(nVar),'))']);
,因为该字符串是实际求值的,所以它将起作用;但是,eval
的使用 通常不鼓励 出于多种原因,仅出于完整性(以及使球滚动的快速而肮脏的方式)而出现.
which will work since the string is actually evaluated; however, the use of eval
is typically discouraged for a number of reasons and is only presented for completeness (and a quick and dirty way to get the ball rolling).
另一种选择是使用将向量x
转换为单元格数组并使用以逗号分隔的列表以以下方式扩展:
Another option is to use convert the vector x
into a cell array and use comma-separated list expansion in the following manner:
splay = @(x) fun(x{:});
funMiddleMan = @(x) splay(mat2cell(x(:),ones(1,numel(x)),1));
不一定是最佳选择,但可以使用.
which is not necessarily optimal but works.
这篇关于Matlab:如何将多变量符号表达式转换为fminsearch可以使用的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!