What am I doing wrong!?
Show older comments
Hi,
I have the following code, it's part of a larger file that is trying (trying being the crucial word here) to perform optimisation using powell's method:
% testing
clear
a = zeros(1,1);
x0 = [0.2, 0.4, 0.6];
s1 = [0.4, 0.4, 1.6];
dx1 = a*x0;
x1 = x0 + dx1;
func = (x1(1)-x1(2))^2+2*(x1(2)-x1(3))^2+3*(x1(3)-1)^2;
[a] = feval(func, x1(1), x1(2), x1(3));
What I am trying to do is find the value of 'a' that minimises 'func'?
Thanks
Accepted Answer
More Answers (3)
Sean de Wolski
on 7 Feb 2012
Syntax issues:
a = zeros(1,1);
x0 = [0.2, 0.4, 0.6];
s1 = [0.4, 0.4, 1.6];
dx1 = a*x0;
x1 = x0 + dx1;
func = @(x)(x(1)-x(2))^2+2*(x(2)-x(3))^2+3*(x(3)-1)^2;
a = fminsearch(func, x1(1:3));
Matt Kindig
on 7 Feb 2012
This is not the approach you want to follow. First, you are calling feval, which will not minimize anything, only evaluate a specified. Instead, you will need one of the solvers in the Optimization Toolbox that is designed to minimize a function, such as fminunc. You will pass a function handle into fminunc that defines your function with the variable you wish to change (a) as the input parameter. Something like this should work:
x0 = [0.2, 0.4, 0.6];
s1 = [0.4, 0.4, 1.6]; %note that you don't use this anywhere
func = @(a) ((a+1)*(x0(1)-x0(2))).^2 + 2*((a+1)*(x0(2)-x0(3))).^2 + 3*( (a+1)*(x0(3)-1)).^2;
a = fminunc(func, 0);
Kevin Holst
on 7 Feb 2012
I'd suggest using the following code, it's not pretty, but it gets the job done without any toolboxes.
x0 = [0.2, 0.4, 0.6];
x1 = @(n,a) (1+a)*x0(n);
func = @(a)(x1(1,a)-x1(2,a))^2+2*(x1(2,a)-x1(3,a))^2+3*(x1(3,a)-1)^2;
a = fminsearch(func, 0);
Categories
Find more on Startup and Shutdown 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!