필터 지우기
필터 지우기

Alternatives for passing variables efficiently to anonymous function

조회 수: 3 (최근 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

채택된 답변

Ameer Hamza
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
Carlos Acasuso
Carlos Acasuso 2020년 12월 2일
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!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by