首先在matlab新建檔案儲存為goldmin.mfunction[x,y] = goldmin(f,xa,xb,s)% 黃金分割法求解函式最小值% 輸入% f 待最佳化函式% a,b 區間% s 精度% 輸出% x 最優解% y 最優解對應的最小值%%g = (sqrt(5)-1)/2; % 黃金分割比,0.618a = xa;b = xb;x2 = a + g*(b-a);x1 = a + b - x2;y1 = f(x1);y2 = f(x2);while abs(b-a) > s if y1<y2 b = x2; x2 = x1; x1 = a + b - x2; end if y1>=y2 a = x1; x1 = x2; x2 = a + b - x1; end y1=f(x1); y2 = f(x2);endx = x1;y = f(x);然後在命令區輸入>> f = @(x) 2*x^2-x-1;>> [x,y]=goldmin(f,-1,1,0.001)x = 0.2497y = -1.1250>> 即當x=0.2497時取最小值-1.125
首先在matlab新建檔案儲存為goldmin.mfunction[x,y] = goldmin(f,xa,xb,s)% 黃金分割法求解函式最小值% 輸入% f 待最佳化函式% a,b 區間% s 精度% 輸出% x 最優解% y 最優解對應的最小值%%g = (sqrt(5)-1)/2; % 黃金分割比,0.618a = xa;b = xb;x2 = a + g*(b-a);x1 = a + b - x2;y1 = f(x1);y2 = f(x2);while abs(b-a) > s if y1<y2 b = x2; x2 = x1; x1 = a + b - x2; end if y1>=y2 a = x1; x1 = x2; x2 = a + b - x1; end y1=f(x1); y2 = f(x2);endx = x1;y = f(x);然後在命令區輸入>> f = @(x) 2*x^2-x-1;>> [x,y]=goldmin(f,-1,1,0.001)x = 0.2497y = -1.1250>> 即當x=0.2497時取最小值-1.125