The following program calculates the minimum point of a multi-variable function using random search method. The search selects random points within a given range for each variable.
The function Random_Search1 has the following input parameters:
The function generates the following output:
Here is a sample session to find the optimum for the following function:
y = 10 + (X(1) - 2)^2 + (X(2) + 5)^2
The above function resides in file fx1.m. The search for the optimum 2 variables has the search range between [-10 -10] and [10 10]. The search employs a maximum of 10000 iterations and a function tolerance of 1e-7:
>> [XBest,BestF,Iters]=Random_Search1(2, [-10 -10], [10 10], 1e-7, 10000, 'fx1')
XBest =
2.4200 -4.6230
BestF =
10.3185
Iters =
10000
Keep in mind that your results will most likely be different since the algorithm uses random numbers.
Here is the MATLAB listing:
function y=fx1(X, N) y = 10 + (X(1) - 2)^2 + (X(2) + 5)^2; end function [XBest,BestF,Iters]=Random_Search1(N,XLo,XHi,Eps_Fx,MaxIter,myFx) % Function performs multivariate optimization using the % random search method. % % Input % % N - number of variables % XLo - array of lower values % XHi - arra of higher values % Eps_Fx - tolerance for difference in successive function values % MaxIter - maximum number of iterations % myFx - name of the optimized function % % Output % % XBest - array of optimized variables % BestF - function value at optimum % Iters - number of iterations % XBest = XLo + (XHi - XLo) * rand(N); BestF = feval(myFx, XBest, N);; LastBestF = 100 * BestF + 100; Iters = 0; for i=1:MaxIter Iters = Iters + 1; X = XLo + (XHi - XLo) * rand(N); F = feval(myFx, X, N); if F < BestF XBest = X; LastBestF = BestF; BestF = F; end if abs(LastBestF - BestF) < Eps_Fx break end end
Copyright (c) Namir Shammas. All rights reserved.