1
+ clc
2
+ clear
3
+ close all
4
+ %% defining three hump camel function
5
+ three_hump_camel = @(X ,Y ) 2 * X .^ 2 - 1.05 * X .^ 4 + X .^ 6 / 6 + X .* Y + Y .^ 2 ;
6
+ %% surface ploting three hump camel function
7
+ [X ,Y ] = meshgrid(-5 : .1 : 5 , - 5 : .1 : 5 );
8
+ Z = three_hump_camel(X ,Y );
9
+ % display the surface plot of the function
10
+ figure(1 )
11
+ surf(X ,Y ,Z )
12
+ title(' surface plot of three hump camel functoin' );
13
+ xlabel(' x(1)' );
14
+ ylabel(' x(2)' );
15
+ zlabel(' threeHumpCamel' );
16
+ shading interp
17
+ %% algorithm implementation
18
+ phi_ = @(x ,r ) 2 * x(1 )^2 - 1.05 * x(1 )^4 + (x(1 )^6 )/6 + x(1 )*x(2 ) + x(2 )^2 - r * (1 /(-x(1 )-5 ) + 1 /(-x(2 )-5 ) + 1 /(x(1 )-5 ) + 1 /(x(2 )-5 ));
19
+ % defining variables
20
+ r = 1000.0 ;
21
+ c = 0.01 ;
22
+ epsilon = 0.005 ;
23
+ options = optimoptions(@fminunc ,' Algorithm' ,' quasi-newton' );
24
+ % display contour plot and converging points
25
+ figure(2 )
26
+ contour(X ,Y ,Z );
27
+ title(' contour of f(x,y) converges at black point' );
28
+ xlabel(' x(1)' );
29
+ ylabel(' x(2)' );
30
+ shading interp
31
+ hold on
32
+ % declaring initial point x1
33
+ x1 = [-4.5 , 2.5 ];
34
+ f1 = three_hump_camel(x1(1 ), x1(2 ));
35
+ scatter(x1(1 ),x1(2 ),' *' );
36
+ iteration = 0 ;
37
+ % while function not converge keep iterating
38
+ while true
39
+ iteration = iteration + 1 ;
40
+ phi = @(x )phi_(x ,r );
41
+ [x2 ,opt_phi ] = fminunc(phi , x1 , options );
42
+ f2 = three_hump_camel(x2(1 ), x2(2 ));
43
+ dx = x2 - x1 ;
44
+ quiver(x1(1 ),x1(2 ),dx(1 ),dx(2 ),0 );
45
+ % convergence check
46
+ if abs((f2 - f1 )/f2 ) <= epsilon
47
+ min_f = f2 ;
48
+ x_star = x2 ;
49
+ display(' function Converged!' );
50
+ fprintf(' Number of Iteration taken to converge = %i\n ' , iteration );
51
+ fprintf(' Minimum value of function = %f\n ' , min_f );
52
+ display(' Optimal point is' );
53
+ display(x_star );
54
+ scatter(x_star(1 ),x_star(2 ),' k*' );
55
+ break
56
+ end
57
+ scatter(x2(1 ),x2(2 ),' *' );
58
+ r = c * r ;
59
+ x1 = x2 ;
60
+ f1 = f2 ;
61
+ end
62
+ legend(' contour' ,' intermediate point' ,' direction of minima' );
63
+ hold off
0 commit comments