58 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			Matlab
		
	
	
	
	
	
			
		
		
	
	
			58 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			Matlab
		
	
	
	
	
	
| function [a, b, k, n] = min_bisection(fun_expr, alpha, beta, epsilon, lambda)
 | |
| % Bisection method for finding the local minimum of a function.
 | |
| %
 | |
| % fun_expr: (symbolic expression over x) The symbolic expression of the
 | |
| %           objective function
 | |
| % alpha:    (number) The starting point of the interval in which we seek
 | |
| %           for minimum
 | |
| % beta:     (number) The ending point of the interval in which we seek
 | |
| %           for minimum
 | |
| % epsilon:  (number) The epsilon value (distance from midpoint)
 | |
| % lambda:   (number) The lambda value (accuracy)
 | |
| %
 | |
| % return:
 | |
| %  a:       (vector) Starting points of the interval for each iteration
 | |
| %  b:       (vector) Ending points of the interval for each iteration
 | |
| %  k:       (number) The number of iterations
 | |
| %  n:       (number) The calls of objective function fun_expr
 | |
| %
 | |
| 
 | |
| 
 | |
| 
 | |
| % Error checking
 | |
| if alpha > beta || 2*epsilon >= lambda || lambda <= 0
 | |
|     error ('Input criteria not met')
 | |
| end
 | |
| 
 | |
| % Init
 | |
| a = alpha;
 | |
| b = beta;
 | |
| n = 0;
 | |
| fun = matlabFunction(fun_expr);
 | |
| 
 | |
| % wrapper call count function
 | |
| function r = count_fun(x)
 | |
|     n = n + 1;
 | |
|     r = fun(x);
 | |
| end
 | |
| 
 | |
| k=1;
 | |
| while b(k) - a(k) > lambda
 | |
|     % bisect [a,b]
 | |
|     mid = (a(k) + b(k)) / 2;
 | |
|     x_1 = mid - epsilon;
 | |
|     x_2 = mid + epsilon;
 | |
|     
 | |
|     % set new search interval
 | |
|     k = k + 1;
 | |
|     if count_fun(x_1) < count_fun(x_2)
 | |
|         a(k) = a(k-1);
 | |
|         b(k) = x_2;
 | |
|     else
 | |
|         a(k) = x_1;
 | |
|         b(k) = b(k-1);
 | |
|     end
 | |
| end
 | |
| 
 | |
| end
 |