MATLAB: Index exceeds the number of array elements (1).

lagrange

hi guys.
I'm beginer. Can you help me to fix the errors?
Thank you for your supporting.
syms x y lambda dx dy
clc
f=x^2*y;
c=x^2+2*y^2;
k=6;
L=f-lambda*(c-k);
Lx=diff(L,x);
Ly=diff(L,y);
root=solve(Lx,Ly,c==k,x,y,lambda);
X=root.x;
Y=root.y;
Lambda=root.lambda;
Lxx=diff(Lx,x);
Lxy=diff(Lx,y);
Lyy=diff(Ly,y);
dc=(diff(c,x)*dx)+(diff(c,y)*dy);
d2L=Lxx*(dx)^2+2*Lxy*(dx*dy)+Lyy*(dy)^2;
for a=1:4
d=solve(subs(dc,[x,y],[X(a),Y(a)]),dx);
newd2L=solve(subs(d2L,[x,y,lambda,dx],[X(a),Y(a),lambda(a),d]));
finald2L=subs(newd2L,dy,1);
if finald2L > 0
disp ('Local minimum point subject to the constraint at x=');
disp(X(a));
disp('y=');
disp(Y(a));
elseif finald2L ==0
disp ('Function does not have extreme at x=');
disp(X(a));
disp('y=');
disp(Y(a));
else
disp ('Local maximum point subject to the constraint at x=');
disp(X(a));
disp('y=');
disp(Y(a));
end
end

Best Answer

If you subs in a particular value for lambda then after the subs() d2L contains only dy, and since you did not specify a variable to solve for, newd2L contains the solution for dy. The expression contains dy^2 times a constant, so the solution comes out as a pair of 0's. Then in the next line you try to subs for dy, but dy is already gone.
I think your logic is wrong there... but I speculated that since you do not seem to want to substitute Lambda(a) for lambda, that perhaps you are wanting to hold on to lambda in the expression and solve for lambda there.
syms x y lambda dx dy
f = x^2*y;
c = x^2+2*y^2;
k = 6;
L = f-lambda*(c-k);
Lx = diff(L,x);
Ly = diff(L,y);
root = solve(Lx,Ly,c == k,x,y,lambda);
X = root.x;
Y = root.y;
Lambda = root.lambda;
Lxx = diff(Lx,x);
Lxy = diff(Lx,y);
Lyy = diff(Ly,y);
dc = (diff(c,x)*dx)+(diff(c,y)*dy);
d2L = Lxx*(dx)^2+2*Lxy*(dx*dy)+Lyy*(dy)^2;
for a = 1:4
d = solve(subs(dc,[x,y],[X(a),Y(a)]),dx);
newd2L = solve(subs(d2L,[x,y,dx],[X(a),Y(a),d]),lambda);
finald2L = subs(newd2L,dy,1);
if finald2L > 0
disp ('Local minimum point subject to the constraint at x = ');
disp(X(a));
disp('y = ');
disp(Y(a));
elseif finald2L == 0
disp ('Function does not have extreme at x = ');
disp(X(a));
disp('y = ');
disp(Y(a));
else
disp ('Local maximum point subject to the constraint at x = ');
disp(X(a));
disp('y = ');
disp(Y(a));
end
end
Af
Related Question