Alternatives for passing variables efficiently to anonymous function
2 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Ameer Hamza
on 2 Dec 2020
Edited: Ameer Hamza
on 2 Dec 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 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!