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
可实现符号函数转换为句柄的功能
以上程序看来是多余了。
在许多情况下,很需要。好像 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
可实现符号函数转换为句柄的功能
以上程序看来是多余了。