Conversion from symbolic to matlabFunction and writing the result to a file

3 ビュー (過去 30 日間)
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2022 年 7 月 20 日
回答済み: Alan Weiss 2022 年 7 月 21 日
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
then I get the following function
function 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)
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,

回答 (1 件)

Alan Weiss
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]
f = 
When it comes time to do stuff with f, you can set m = 0.
Alan Weiss
MATLAB mathematical toolbox documentation

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by