Borrar filtros
Borrar filtros

Alternatives for passing variables efficiently to anonymous function

3 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 2 de Dic. de 2020
Editada: Ameer Hamza el 2 de Dic. de 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 comentarios
Carlos Acasuso
Carlos Acasuso el 2 de Dic. de 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!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by