我有一个匿名函数,希望将其以字符串形式操作后再使用fsolve。但是当我这样做时,匿名函数中对常量的引用会丢失,导致fsolve失败。
问题可以很容易地说明:
以下代码能够正常工作:
A=3;
myfun=@(x)sin(A*x);
x = fsolve(@(x)myfun(x),[1 4],optimoptions('fsolve','Display','off'))
以下代码会抛出错误,详细解释在这里说明:
A=3;
myfun=@(x)sin(A*x);
mystring=func2str(myfun);
%string operations would go here such as strrep(mystring,'A','A^2') or whatever
myfun2=str2func(mystring);
x = fsolve(@(x)myfun2(x),[1 4],optimoptions('fsolve','Display','off'))
有没有一种安全的方法可以在保留对常量参数的引用的同时操作匿名函数?
更多信息:
具体来说,我正在编写一个简单的包装器,以便让fsolve在简单情况下接受虚数。以下示例演示了一个工作示例,不使用常量参数:
myeqn=@(x)0.5*x^2-5*x+14.5;
cX0=1+1*1i;
f1=strrep(func2str(myeqn),'@(x)','');
f2=strrep((f1),'x','(x(1)+(x(2))*1i)');
f3=strcat('@(x)[real(',f2,'); imag(',f2,')]');
fc=str2func(f3);
opts=optimoptions('fsolve','Display','off');
result=arrayfun(@(cinput)[1 1i]*(real(fsolve(fc,[real(cinput);imag(cinput)],opts))),cX0)
与上面失败的示例一样,如果我在包装器中包含一个参数,该过程将以与上述相同的错误失败。
subs
函数)非常有帮助。 - Daniel