How to (efficiently) replace eval() with subs() for symbolic equations
Afficher commentaires plus anciens
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 commentaires
Walter Roberson
le 15 Déc 2018
btf = matlabFunction(bt*str2sym(Fs), 'vars', {s, bt})
Nat A
le 15 Déc 2018
Walter Roberson
le 15 Déc 2018
why are you constructing string of those instead of symbolic expression ?
Nat A
le 15 Déc 2018
Walter Roberson
le 16 Déc 2018
After that change you would just use that return value without str2sym as it is already sym. You would still use matlabFunction though.
Nat A
le 17 Déc 2018
Walter Roberson
le 17 Déc 2018
The implication would seem to be that somehow it was thinking that ft was initialized to symbolic before that point. I looked back over your code and code not see it, but perhaps I was not looking at the current version ?
Walter Roberson
le 18 Déc 2018
Modifié(e) : Walter Roberson
le 18 Déc 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.
Nat A
le 19 Déc 2018
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Code Performance dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!