求多变量函数的最小值

Find the minimum of a multi-variable function

题目:求f(x,y)=x^2+y^2-2*x-6*y+14中的最小值window [0,2]×[2,4] x 和 y 的增量为 0.01。

我的做法:求一阶偏导数fx和fy。临界点同时满足方程 fx(x,y) = 0 和 fy(x,y) = 0。找到二阶偏导数 fxx(x,y)、fyy(x,y) 和 fxy(x,y) 以便找到 D.

clc
clear all
syms x y
fun=x^2+y^2-2*x-6*y+14;
fx=diff(fun,x);
fy=diff(fun,y);
pt=solve(fx==0,fy==0);
sol = struct2array(pt)
fxx=diff(fx,x);
fyy=diff(fy,y);
fxy=diff(fx,y);
D=subs(fxx,[x y],[1 3])*subs(fyy,[x y],[1 3])-(subs(fxy,[x y],[1 3]))^2
fxx_val=subs(fxx,[x y],[1 3])
minimum_value=subs(fun,[x y],[1 3])

我对所提问题的处理是否正确?除了 window 和 increment 提到的那个问题。任何提示或解决方案将不胜感激。
提前致谢。

使用函数求值优化方法代替梯度

请仔细阅读代码


f = @(x,y)x.^2+y.^2-2.*x-6.*y+14;

% x range
x_lb = 0;
x_ub = 2;

% y range
y_lb = 2;
y_ub = 4;

step = 0.01;

% lower bound of x, initial guess as xmin
xmin = x_lb;

% lower bound of y, initial guess as ymin
ymin = y_lb;

% f at the lower bounds, initial  fmin 
fmin = f(xmin, ymin);

for x = x_lb:step:x_ub

    for y = y_lb:step:y_ub
        % function evaluation
        fval = f(x, y);

        %replace fmin if the newly evaluated f is less than the actual fmin
        if fval < fmin
            fmin = fval;

            % save current x and y where f is minimum 
            xmin = x;
            ymin = y;

        end
    end

end

解决方案

xmin = 1;
ymin = 3;
fmin = 4;

我建议利用 Matlab 的功能来计算矩阵。然后,不需要循环。

% your function, look up anonymous functions 
func = @(x,y) x.^2 + y.^2 - 2.*x - 6.*y + 14;

% get matrices for you x- and y-window
[xg, yg] = meshgrid(0:.01:2, 2:0.01:4);

% compute all in one call
result = func(xg,yg);

% find total minimum
minimum = min(result(:));

% find the index of the (first) minimum, for other equations, there might
% be more than one
ind = find(result==minimum, 1);

% Output the result
fprintf('The minimum (%d) is located at x: %d, y: %d.\n', minimum,  xg(ind), yg(ind));