fminsearch with multiple variables
6 views (last 30 days)
Show older comments
Andrew Waller
on 19 Oct 2016
Commented: Andrew Waller
on 19 Oct 2016
I have an assignment that I have to use fminsearch to find minimum potential energy. I've seen similar questions asked all giving different styled answers but haven't had any luck getting it to work. Basically I'm given an equation for potential energy in respect to x and y. From (0:90) degrees I have to use the fminsearch to find minimum PE and x,y. I know this is a basic function but I've never used it before and it's giving me errors.
t=(0:90);
x=20.*sin(degtorad(t));
y=20.*cos(degtorad(t));
p = 4.*(x.^2)-0.1.*(x.^2)+4.*abs(y.^2).^(1.8);
Preferably I'd like my fminsearch to output x,y and the p values at once. Is this possible in just one function?
0 Comments
Accepted Answer
Walter Roberson
on 19 Oct 2016
fminsearch is only for application to function handles. For discrete variables:
[X, Y] = ndgrid(x, y);
p = 4.*(X.^2)-0.1.*(X.^2)+4.*abs(Y.^2).^(1.8);
[minval, minidx] = min(p);
best_x = X(minidx); best_y = Y(minidx); best_p = p(minidx);
7 Comments
Walter Roberson
on 19 Oct 2016
For R2016a and earlier, the first non-comment in your PE.m has to be "function". If there is anything executable for that, you would get that error.
"Not sure why we are required to use fminsearch"
I suspect that you have not specified the problem correctly here. The way you have specified it here is that you are given a vector of t values, each of which corresponds to a degree angle on a circle of radius 20, and that the minimum is to be found from all combinations of x and y so implied.
Hmmm.... I guess I read in the need to find it over all of the combinations where it might not have been present.
function [best_x, best_y, best_p] = PE(t)
x=20.*sin(degtorad(t));
y=20.*cos(degtorad(t));
p = 4.*(x.^2)-0.1.*(x.^2)+4.*abs(y.^2).^(1.8);
[minval, minidx] = min(p);
best_x = x(minidx); best_y = y(minidx); best_p = p(minidx);
Now, what would make sense to use fminsearch over is the possibility that you did not know the t in advance and were asked to find it and you did not ask to output the x and y values and the function was only expected to be passed scalar t. In that combination of circumstances,
function p = PE(t)
x=20.*sin(degtorad(t));
y=20.*cos(degtorad(t));
p = 4.*(x.^2)-0.1.*(x.^2)+4.*abs(y.^2).^(1.8);
and then you fminsearch on PE . It does not need multiple parameters in this situation.
More Answers (0)
See Also
Categories
Find more on Linear Least Squares in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!