What am I doing wrong!?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
Kevin Holst
am 7 Feb. 2012
Ah I see the problem now. In your original post you had
s1 = [0.4, 0.4, 1.6];
but nothing using s1 in it. Now that I see what s1 is used for here's the solution:
x0 = [0.2, 0.4, 0.6];
s1 = [0.4, 0.4, 1.6];
x1 = @(n,a) x0(n) + s1(n)*a;
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);
a = 0.1364
Weitere Antworten (3)
Sean de Wolski
am 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
am 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
am 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);
Siehe auch
Kategorien
Mehr zu Linear Least Squares finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!