Info
This question is closed. Reopen it to edit or answer.
Ι have a problem finding a minimum
1 view (last 30 days)
Show older comments
I created a fuction by writting
function [y]=h(x)
y=(x^8+P(x))^2
end
and I saved it as h.m
then I wrote [x,fval]=fminsearch(h,[2,3]) and it says its error FYI P(x) is a polynomial which i created in the main file
2 Comments
Walter Roberson
on 6 Jan 2016
Duplicates earlier http://uk.mathworks.com/matlabcentral/answers/262889-have-a-problem-finding-a-minimum but this version has an answer so I am merging into this one.
Answers (2)
the cyclist
on 6 Jan 2016
Edited: the cyclist
on 6 Jan 2016
According to the documentation, fminsearch is expecting a function handle there, not the name of an M-file. (But maybe that is supposed to work, too. I'm not sure.)
Maybe try defining h(x) as a anonymous function instead? For example, the following code worked for me:
P = @(x) x-0.4;
h = @(x)(x^2+P(x))^2;
fminsearch(h,2.5)
Also, but I am just guessing here, you may have wanted to use ".^" for the powers, since I am guessing you are not doing powers of matrices.
0 Comments
Walter Roberson
on 6 Jan 2016
Your P is undefined within your function. With some care you could effectively import it from an enclosing function (but you probably didn't). However, with your definition of P=polyfit(X,Y.',7) you need to understand that the result is a vector of values, not an interpolating function, and as it is a vector of values P(x) is only valid when x is an index into the vector, not when x is an arbitrary value being fitted.
You would need something like
P = polyfit(X, Y.', 7);
interpP = @(x) polyval(P,x);
h = @(x) (x.^2 + interpP(x)).^2;
fminsearch(h, 2.5)
or more compactly
P = polyfit(X, Y.', 7);
h = @(x) (x.^2 + polyval(P, x)).^2;
fminsearch(h, 2.5)
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!