필터 지우기
필터 지우기

Passing Structure through fminsearch

조회 수: 23 (최근 30일)
Leah
Leah 2024년 4월 1일 21:58
댓글: Leah 2024년 4월 2일 15:27
There is a code that I am trying to improve by eliminating the global variables. The only issue is is that the function that is used for fminsearch has other functions inside that need the global variables. So I am thinking of passing a structure through fminsearch with an anonymous function. However, when I run the new code it seams like fminsearch is not performing properly becuase it goes at double the speed and not return a good answer.
Here is the original code calling the fminsearch function:
[p,c] = fminsearch('cost',p0); % OPTIMIZATION
%function for fminsearch:
function [c,meanErr] = cost(p)
global PHIs TAUs Parameters
%rest of code
end
Instead of having the variables of PHIs, TAUs, and Parameters as global, I send them to a structure S. Here is how I am trying to pass the structure through fminsearch:
S.p = p;
[p,c] = fminsearch(@(p) costLeg(S), S.p); % OPTIMIZATION
%function for fminsearch:
function [c,meanErr] = costLeg(S)
%rest of code
end
Am I passing this structure correctly? How can I double check that I am?
Thanks!

채택된 답변

Matt J
Matt J 2024년 4월 1일 22:10
편집: Matt J 2024년 4월 1일 22:14
If p is the unknown parameter vector, it must be passed separately from the fixed parameters,
S.PHI=...
S.TAU=...
[p,c] = fminsearch(@(p) costLeg(p,S), p0); % OPTIMIZATION
%function for fminsearch:
function [c,meanErr] = costLeg(p,S)
%rest of code
end
  댓글 수: 1
Leah
Leah 2024년 4월 2일 15:27
I thought I tried this at some point but maybe I didn't execute it right. But this works! Thank you!!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Optimization에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by