Problems with minimizing a function

조회 수: 8 (최근 30일)
Gisela
Gisela 2016년 4월 12일
댓글: Walter Roberson 2016년 4월 12일
I need to fit some parameters using the fminsearch command. my plot is the following one.
function fit
load R75
x=ang
y=int
p0=[ 1 1 1]
[p,fval]=fminsearch(@err,p0,x)
p
function err=S(x,p)
S=norm(ycalc-y)
function calc= ycalc(p,x)
ycalc=p(1)*(cos((pi/180)*(x-p(2))))^2+p(3)
x and y are data I load from file R75. What I want to do is to find the values of p that minimize the error S between experimental and calculated value. However I have problems doing this. Can anybody help me?

채택된 답변

John D'Errico
John D'Errico 2016년 4월 12일
편집: John D'Errico 2016년 4월 12일
First of all, do not do a load every time the function is called. This is very inefficient, and will soon cause you to ask how to make your code run more efficiently.
As well, do not call your function fit, in case you have (or ever will need) the curve fitting toolbox. int is another really bad name to use for a variable, as this is the integration tool from the symbolic toolbox.
Next, to answer the current question, you do not pass in any parameters to the function. How should your function know what the values of ang and int are?
As well, you return no arguments from your function. What will a tool like fminsearch attempt to minimize?
Finally, you are misusing function handles. This line will not do what you think it does. In fact, I assume it will probably generate an error.
[p,fval]=(@err(p0,x))
Instead, assuming that you just wish to evaluate the sub-function you have called err, just do this:
[p,fval] = err(p0,x);
Overall, it looks like you need to do a LOT of reading. I think you do not understand how to use and write functions at all. Start with
doc function
Also read about function handles. And read about how to use the basic optimization tools in MATLB, like fminsearch.
doc fminsearch
I cannot write everything you need to know, because that would take hours on my part to write, and minutes for you to read.
  댓글 수: 2
Gisela
Gisela 2016년 4월 12일
Thank your for your suggestions but I just realized that I didn't write the fminsearch command. However the script still doesn't run by doing all you proposed.
Walter Roberson
Walter Roberson 2016년 4월 12일
Please post your code

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with Optimization Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by