Effacer les filtres
Effacer les filtres

Alternatives for passing variables efficiently to anonymous function

3 vues (au cours des 30 derniers jours)
Carlos Acasuso
Carlos Acasuso le 2 Déc 2020
Commenté : Ameer Hamza le 3 Déc 2020
Hello,
I have a function as shown below, where I need to solve a system of equations via fsolve in a large loop.
At every iteration within this loop, I am replacing three variables, stored as single-vector arrays, in my system of equations (my system of equations is written as an anonymous function f) and I cannot find a better way than doing so by bringing f to the loop as a string, replacing my numeric variables as strings, and then using str2fun before solving the problem.
This code is very efficient-critical as the single-vector arrays I have to substitute and solve are very large, perhaps >10^6 data points.
function [KinSol] = ResolveKin2(LDamperFL, LDamperFR, SteerRackTravel, f, opts)
x0 = rand(14,1);%<---
KinSol = nan(14,length(LDamperFL)); %<---
for i = 1:size(KinSol,2) %<---
LDamperFL_st = string(LDamperFL(i));
LDamperFR_st = string(LDamperFR(i));
SteerRackTravel_st = string(SteerRackTravel(i));
f = replace(f,["LDamperFL","LDamperFR","xSteerRack"], [LDamperFL_st, LDamperFR_st, SteerRackTravel_st]);
Sfun_R = str2func(f);
x0 = fsolve(Sfun_R, x0, opts);%<---
KinSol(:,i) = x0;%<---
end
end
I have been looking into the options shown here for Passing Extra Parameters, but I'm not being successful in my attempt.
Thanks in advance for your time and help.
Carlos

Réponse acceptée

Ameer Hamza
Ameer Hamza le 2 Déc 2020
Modifié(e) : Ameer Hamza le 2 Déc 2020
Don't bring 'f' as string. Define it as function handle. For example, define f like this
f = @(x, LDamperFL, LDamperFR, xSteerRack) ........
and change the code to something like this
function [KinSol] = ResolveKin2(LDamperFL, LDamperFR, SteerRackTravel, f, opts)
x0 = rand(14,1);%<---
KinSol = nan(14,length(LDamperFL)); %<---
for i = 1:size(KinSol,2) %<---
x0 = fsolve(@(x) f(x,LDamperFL(i),LDamperFR(i),SteerRackTravel(i)), x0, opts);%<---
KinSol(:,i) = x0;%<---
end
end
  6 commentaires
Carlos Acasuso
Carlos Acasuso le 2 Déc 2020
I understand now what was occuring. After the first iteration of the loop, 'f' got overwritten, the variables no longer exist there, hence they're not replaced anymore everafter.
After correcting this to not overwrite 'f', the code takes a very long time of 67s for 1000 iterations.
So now, your code is definitely the best choice and most efficient, thank you very much!
Ameer Hamza
Ameer Hamza le 3 Déc 2020
I am glad to be of help! :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by