How to (efficiently) replace eval() with subs() for symbolic equations

9 views (last 30 days)
Hi,
I've been trying to convert a code I have for modeling a curve into a Simulink model (so, eventually, I'll be able to run automatic parameter estimation). The code itself is comprised of a few different symbolic functions. I previously used the code in Matlab 2012b (where it exectutes very quickly without problems) however I couldn't make it work in Simulink because of the C++ compiler issue. I tried to apply the patches to resolve the compiler problem with no sucess so I gave up and switced over to 2018b. Now the problem seems to be trying to replace the eval() function which is no longer supported. My best solution to date uses sub() and str2sym(). This works but is so slow that it's effectively useless. Does anybody have suggestions on how I can improve the code?
Old version:
for kt=1:nnt
tt=radt(kt); s=alfa/tt; bt=beta/tt; btF=bt.*eval(FF); ft(kt)=sum(real(btF));
end
New version:
btf=@(s,bt) double(bt.*subs(str2sym(Fs)));
for kt=1:nnt
tt=radt(kt); s=alfa/tt; bt=beta/tt; btF=btf(s,bt); ft(kt)=sum(real(btF));
end
For reference, a simplified version of FF is: '(0.1*s)^(1/2)*besselk(0.0, 8.0*(0.1*s)^(1/2))'
I'll include the files being used in case anyone would like to take a look in more detail.
Thanks in advance for any assistance!
  11 Comments
Walter Roberson
Walter Roberson on 18 Dec 2018
Edited: Walter Roberson on 18 Dec 2018
syms Alfa Beta TT
F = simplify(subs(bt.*h_ob_b, {s,bt}, {Alfa/TT, Beta/TT}));
FF = sum(real(subs(F,{Alfa,Beta},{alfa(:), beta(:)})));
FFF = matlabFunction(FF,'File','FFF.m','optimize',true);
ft = FFF(radt);
The creation of the .m file is not especially fast because of the optimization, but the execution for the 1000 points is less than 0.2 seconds.
You might also want to try timing with optimize turned off in the MATLAB function -- taking the tradeoff between the time spend optimizing the code and the time spend executing the optimized code.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 19 Dec 2018
(Reposting as an Answer)
syms Alfa Beta TT
F = simplify(subs(bt.*h_ob_b, {s,bt}, {Alfa/TT, Beta/TT}));
FF = sum(real(subs(F,{Alfa,Beta},{alfa(:), beta(:)})));
FFF = matlabFunction(FF,'File','FFF.m','optimize',true);
ft = FFF(radt);
The creation of the .m file is not especially fast because of the optimization, but the execution for the 1000 points is less than 0.2 seconds.
You might also want to try timing with optimize turned off in the MATLAB function -- taking the tradeoff between the time spend optimizing the code and the time spend executing the optimized code.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!