登录论坛

查看完整版本 : [MATLAB基础] 如何将符号变量定义的函数表达式转换为句柄形式


bodhitreechen
2010-06-27, 15:37
将符号变量定义的函数表达式转换为句柄形式,
在许多情况下,很需要。好像 Matlab 并没有提供
相关的函数(如果哪位知道请告知)。
下面的m文件将把符号变量表达式定义的普通函数,向量值函数,
或矩阵值函数的转为函数句柄。可以直接使用(已经测试过)。


function f=sym2funh(f_s,x_in)

% sym2funh Convert a function f_s expressed in syms to a function handle.
% Here, x_in are syms which stand for varibles, f_s can be a sale-, vector-,
% or matrix- valued function.

syms x
x=x_in;
if isa(f_s, 'sym')
sf0=char(f_s);
else
error('It is expected that the first input argument is a sym which stand for a function.');
end
for itt=1:length(x)
tempstr=['x(',num2str(itt),')'];
sf0=strrep(sf0,char(x(itt)),tempstr);
end
sf=strrep(sf0,'matrix(','');
adjust=double(length(sf0)~=length(sf));
sf=['@(x) ',sf(1:end-adjust)];
sf=strrep(sf,'],[','];[');
f=eval(sf);








P.S.

最近得知matlab自带的函数matlabFunction

可实现符号函数转换为句柄的功能

以上程序看来是多余了。

未注册
2010-11-26, 09:16
非常感谢楼主。我用的matlab版本没有matlabFunction这个函数。你写的这个函数我找了好久了,对我的帮助很大!

shengsheng
2010-12-07, 00:58
确实不错!如果能举个具体的例子的话,那就更好了。

1027765819
2012-11-19, 16:21
请问楼主自带的函数名称是什么?