Conversion from symbolic to matlabFunction and writing the result to a file
2 次查看(过去 30 天)
显示 更早的评论
Hello friends,
I have a simple problem but it seems difficult for me to fix. I want to create a matlabFunction from a symbolic vector and write that matlab function to a file. But, prior to converting the symbolic vector I have to do some manipulations to the symbolic vector. Let's take an example and you will see what I mean exactly. Consider the following symbolic vector f
syms Dm0 Ds0 Ds1 dt
f = [(2.*Dm0.*dt.^(1./2) - Ds0.*Ds1.*dt.^(1./2))./(2.*Ds0); 1; 0]
the problem is that the last 2 elements are not variables. So, if I type
matlabFunction(f,'File','fname','Vars',[Dm0,Ds0,Ds1,dt],'Outputs',{'EZ'});
then I get the following function
function EZ = fname(Dm0,Ds0,Ds1,dt)
%FNAME
% EZ = FNAME(DM0,DS0,DS1,DT)
% This function was generated by the Symbolic Math Toolbox version 8.6.
% 20-Jul-2022 16:21:27
t2 = sqrt(dt);
EZ = [(Dm0.*t2.*2.0-Ds0.*Ds1.*t2)./(Ds0.*2.0);1.0;0.0];
I am not happy with this since later I cannot do vector calculus due to the presence of constants. What I wish is to write the following matlab function to a file (I am not interested to just create the matlab function)
@(Dm0,Ds0,Ds1,dt)[(Dm0.*sqrt(dt).*2.0-Ds0.*Ds1.*sqrt(dt))./(Ds0.*2.0);1.0+0.*Ds0;0.*Ds0]
I can fix this problem by converting f to a character and then via character manipulations I can first create the character '[(Dm0.*sqrt(dt).*2.0-Ds0.*Ds1.*sqrt(dt))./(Ds0.*2.0);1.0+0.*Ds0;0.*Ds0]' and then apply char2func. But, the issue then would be that it just creates the matlab function and does not write it into a file (unfortunately, there is not a command like char2func(f,'File',filename,'Vars',[Dm0,Ds0,Ds1,dt],'Outputs',{'f'});.
Why I am interested to write the matlab function to a file? In reality my original symbolic vector f is extremely long. So, if I just turn it into a matlab function then matlabFunction does not optimize the code (so, later when I want to evaluate my matlab function its speed is low).
Any idea?
thanks in advance,
Babak
0 个评论
回答(1 个)
Alan Weiss
2022-7-21
Would it be possible to do the following: create a multiplier variable m in addition to the other variables?
syms Dm0 Ds0 Ds1 dt m
f = [(2.*Dm0.*dt.^(1./2) - Ds0.*Ds1.*dt.^(1./2))./(2.*Ds0); 1 + m*Ds0; m*Ds0]
matlabFunction(f,'File','fname','Vars',[Dm0,Ds0,Ds1,dt,m],'Outputs',{'EZ'});
When it comes time to do stuff with f, you can set m = 0.
Alan Weiss
MATLAB mathematical toolbox documentation
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Code Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!