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

조회 수: 6 (최근 30일)
Nat A
Nat A 2018년 12월 15일
답변: Walter Roberson 2018년 12월 19일
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
Walter Roberson
Walter Roberson 2018년 12월 18일
편집: Walter Roberson 2018년 12월 18일
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.
Nat A
Nat A 2018년 12월 19일
That's great, thanks so much!

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2018년 12월 19일
(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.

추가 답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by