Alternatives for passing variables efficiently to anonymous function
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Ameer Hamza
2020-12-2
编辑:Ameer Hamza
2020-12-2
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!