Problem: MATLAB Implementation of Dragonfly Algorithm and Auxiliary Functions

The problem requires implementing MATLAB functions for piecewise/benchmark calculations, initialization, distance, Levy flight, the Dragonfly Algorithm for optimization, and a function to get function details.


Input/Output: The problem receives specifications for MATLAB functions (Ufun, F1-F23, Get_Functions_details, initialization, distance, Levy, DA) including function definitions, algorithm steps, variable names, and test cases. It generates correct MATLAB function codes for each specified function that adhere to the input specifications and pass all provided test cases.

Required dependencies:

Sub-steps:
step_number: 1
step_description_prompt: Please write a MATLAB function named Ufun that implements a piecewise function calculation based on input parameters x, a, k, m. The function is defined as function o = Ufun(x, a, k, m). Compute the output o as the sum of two terms: the first term is k multiplied element-wise by (x - a) raised to the power of m, multiplied element-wise by the logical array where x is greater than a; the second term is k multiplied element-wise by (-x - a) raised to the power of m, multiplied element-wise by the logical array where x is less than -a. Functions called in the provided code are assumed to be already defined and do not need to be redefined.
function_header: function o=Ufun(x,a,k,m)

end
test_cases: clear; clc;
rng(42);
correct = 32.0000;
x = [-3, -1, 0, 1, 3];
a = 1;
k = 2;
m = 3;
result = Ufun(x, a, k, m);
val = sum(result);
if val~=correct
    error('Wrong')
end
correct = 500.0000;
x = [-4, -6, 2, 3, 5];
a = 2;
k = 5;
m = 3;
result = Ufun(x, a, k, m);
val = sum(result);
if val~=correct
    error('Wrong')
end
correct = 1302.00000;
x = [-1, -2, 5, 6, 4];
a = 1;
k = 6;
m = 3;
result = Ufun(x, a, k, m);
val = sum(result);
if val~=correct
    error('Wrong')
end
disp('Completely right!')

step_number: 2
step_description_prompt: Please use MATLAB code to generate a function named F1 that computes the sum of the squares of the elements of the input vector x. The function definition is function o = F1(x). The algorithm flow is to calculate the square of each element in x using element-wise exponentiation (x.^2) and then sum all the squared elements using sum().

Please use MATLAB code to generate a function named F2 that computes the sum of the absolute values of the elements of input vector x plus the product of the absolute values of the elements of x. The function definition is function o = F2(x). The algorithm flow is to compute the sum of absolute values of x with sum(abs(x)) and the product of absolute values of x with prod(abs(x)), then add these two results.

Please use MATLAB code to generate a function named F3 that computes the sum of the squares of the cumulative sums of the first i elements of input vector x for i from 1 to the number of elements in x. The function definition is function o = F3(x). The algorithm flow is: 1. Get the number of elements dim as size(x,2). 2. Initialize the output o to 0. 3. For i from 1 to dim: a. Compute the sum of the first i elements of x using sum(x(1:i)). b. Square this sum. c. Add the squared value to o. 4. Return o.

Please use MATLAB code to generate a function named F4 that computes the maximum absolute value of the elements of input vector x. The function definition is function o = F4(x). The algorithm flow is to compute the absolute values of all elements in x with abs(x) and then take the maximum value with max().

Please use MATLAB code to generate a function named F5 that computes the sum of 100*(x(i) - x(i-1)^2)^2 + (x(i-1) - 1)^2 for i from 2 to the number of elements in x. The function definition is function o = F5(x). The algorithm flow is: 1. Get the number of elements dim as size(x,2). 2. Compute the element-wise terms 100*(x(2:dim) - x(1:dim-1).^2).^2 and (x(1:dim-1) - 1).^2. 3. Sum the element-wise sum of these two terms using sum().

Please use MATLAB code to generate a function named F6 that computes the sum of the squares of the absolute values of (each element of input vector x plus 0.5). The function definition is function o = F6(x). The algorithm flow is to compute abs(x + 0.5) element-wise, square the result with .^2, and then sum all the squared values with sum().

Please use MATLAB code to generate a function named F7 that computes the sum of the product of each element's index (starting from 1) and the fourth power of the element, plus a random number between 0 and 1. The function definition is function o = F7(x). The algorithm flow is: 1. Get the number of elements dim as size(x,2). 2. Create an index vector [1:dim]. 3. Compute the element-wise product of the index vector and x.^4. 4. Sum these products with sum() and add a random number generated by rand().

Please use MATLAB code to generate a function named F8 that computes the sum of -x.*sin(sqrt(abs(x))) for all elements in input vector x. The function definition is function o = F8(x). The algorithm flow is to compute sqrt(abs(x)) element-wise, apply sin() to the result, multiply by -x element-wise, and then sum all the results with sum().
test_cases: clear; clc;
rng(42);
correct = 6659.399639;
x = [1.2, -0.5, 2.3, -1.8, 0.7];
val = F1(x) + F2(x) + F3(x) + F4(x) + F5(x) + F6(x) + F7(x) + F8(x);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong')
end
correct = 116785.710695;
x = [1.6, -0.3, 5.6, -1.7, 0.9];
val = F1(x) + F2(x) + F3(x) + F4(x) + F5(x) + F6(x) + F7(x) + F8(x);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong')
end
correct = 24863.690416;
x = [2.5, -1.6, 2.6, -3.2, 1.3];
val = F1(x) + F2(x) + F3(x) + F4(x) + F5(x) + F6(x) + F7(x) + F8(x);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong')
end
disp('Completely right!')

step_number: 3
step_description_prompt: Please write MATLAB functions named F9, F10, F11, F12, F13, F14, F15, F16, F17 that implement the following benchmark functions with exact logic, input/output, and dependencies (note: Ufun is assumed to be pre-defined and available):


### Function F9 (Rastrigin Function)
Function definition: `function o = F9(x)`  
Algorithm steps:  
1. Compute `dim` as the number of columns in `x` using `size(x,2)`.  
2. Calculate `o` as the sum of `x.^2 - 10*cos(2*pi.*x)` plus `10*dim`.  


### Function F10 (Ackley Function)
Function definition: `function o = F10(x)`  
Algorithm steps:  
1. Compute `dim` as the number of columns in `x` using `size(x,2)`.  
2. Calculate `o` as `-20*exp(-0.2*sqrt(sum(x.^2)/dim)) - exp(sum(cos(2*pi.*x))/dim) + 20 + exp(1)`.  


### Function F11 (Griewank Function)
Function definition: `function o = F11(x)`  
Algorithm steps:  
1. Compute `dim` as the number of columns in `x` using `size(x,2)`.  
2. Calculate `o` as `sum(x.^2)/4000 - prod(cos(x./sqrt(1:dim))) + 1`.  


### Function F12
Function definition: `function o = F12(x)`  
Algorithm steps:  
1. Compute `dim` as the number of columns in `x` using `size(x,2)`.  
2. Compute the first term: `(pi/dim) * [10*(sin(pi*(1 + (x(1)+1)/4)))^2 + sum(((x(1:dim-1)+1)./4).^2 .* (1 + 10*(sin(pi*(1 + (x(2:dim)+1)./4))).^2)) + ((x(dim)+1)/4)^2]`.  
3. Compute the second term: `sum(Ufun(x,10,100,4))`.  
4. Set `o` as the sum of the first and second terms.  


### Function F13
Function definition: `function o = F13(x)`  
Algorithm steps:  
1. Compute `dim` as the number of columns in `x` using `size(x,2)`.  
2. Compute the first term: `0.1 * [(sin(3*pi*x(1)))^2 + sum((x(1:dim-1)-1).^2 .* (1 + (sin(3*pi*x(2:dim))).^2)) + ((x(dim)-1)^2)*(1 + (sin(2*pi*x(dim))).^2)]`.  
3. Compute the second term: `sum(Ufun(x,5,100,4))`.  
4. Set `o` as the sum of the first and second terms.  


### Function F14
Function definition: `function o = F14(x)`  
Algorithm steps:  
1. Define matrix `aS` as:  
   `[-32 -16 0 16 32 -32 -16 0 16 32 -32 -16 0 16 32 -32 -16 0 16 32 -32 -16 0 16 32; -32 -32 -32 -32 -32 -16 -16 -16 -16 -16 0 0 0 0 0 16 16 16 16 16 32 32 32 32 32]`.  
2. Initialize `bS` as a 1x25 array. For `j = 1:25`:  
   a. Compute `bS(j) = sum((x' - aS(:,j)).^6)`.  
3. Calculate `o = (1/500 + sum(1./(1:25 + bS)))^(-1)`.  


### Function F15 (Keane's Function)
Function definition: `function o = F15(x)`  
Algorithm steps:  
1. Define array `aK` as `[0.1957 0.1947 0.1735 0.16 0.0844 0.0627 0.0456 0.0342 0.0323 0.0235 0.0246]`.  
2. Define array `bK` as `1./[0.25 0.5 1 2 4 6 8 10 12 14 16]`.  
3. Calculate `o = sum((aK - (x(1)*(bK.^2 + x(2)*bK))./(bK.^2 + x(3)*bK + x(4))).^2)`.  


### Function F16 (Six-Hump Camel Back Function)
Function definition: `function o = F16(x)`  
Algorithm steps:  
1. Calculate `o = 4*(x(1)^2) - 2.1*(x(1)^4) + (x(1)^6)/3 + x(1)*x(2) - 4*(x(2)^2) + 4*(x(2)^4)`.  


### Function F17 (Branin Function)
Function definition: `function o = F17(x)`  
Algorithm steps:  
1. Calculate `o = (x(2) - (x(1)^2)*5.1/(4*pi^2) + 5/pi*x(1) - 6)^2 + 10*(1 - 1/(8*pi))*cos(x(1)) + 10`.  


All functions must use the exact variable names, array values, loop ranges, and mathematical operations as specified. Dependencies like `Ufun` are assumed to be pre-defined and accessible.
test_cases: clear; clc;
rng(42);
correct = 143.557619;
x5 = [0.5, 1.2, 0.3, 1.5, 0.8];
x2 = [0.5, 1.2];
x4 = [0.3, 0.7, 1.5, 2.1];
val = F9(x5) + F10(x5) + F11(x5) + F12(x5) + F13(x5) + F14(x2) + F15(x4) + F16(x2) + F17(x2);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
correct = 148.143694;
x5 = [0.6, 2.2, 2.2, 1.6, 0.9];
x2 = [0.1, 1.2];
x4 = [0.3, 0.2, 2.3, 1.1];
val = F9(x5) + F10(x5) + F11(x5) + F12(x5) + F13(x5) + F14(x2) + F15(x4) + F16(x2) + F17(x2);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
correct = 131.306685;
x5 = [0.8, 1.4, 0.3, 1.2, 0.8];
x2 = [0.2, 1.1];
x4 = [0.4, 0.3, 1.1, 2.1];
val = F9(x5) + F10(x5) + F11(x5) + F12(x5) + F13(x5) + F14(x2) + F15(x4) + F16(x2) + F17(x2);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 4
step_description_prompt: Please use MATLAB code to generate functions named F18, F19, F20, F21, F22, F23 that take input x and return output o as specified. Each function must have the exact definition and calculations below:

1. Function F18:
Function definition: function o = F18(x)
Calculation: o = (1 + (x(1) + x(2) + 1)^2 * (19 - 14*x(1) + 3*(x(1)^2) - 14*x(2) + 6*x(1)*x(2) + 3*(x(2)^2))) * (30 + (2*x(1) - 3*x(2))^2 * (18 - 32*x(1) + 12*(x(1)^2) + 48*x(2) - 36*x(1)*x(2) + 27*(x(2)^2)));

2. Function F19:
Function definition: function o = F19(x)
Calculation: Define aH = [3 10 30;.1 10 35;3 10 30;.1 10 35], cH = [1 1.2 3 3.2], pH = [.3689 .117 .2673;.4699 .4387 .747;.1091 .8732 .5547;.03815 .5743 .8828]. Initialize o = 0. Loop i from 1 to 4: o = o - cH(i)*exp(-(sum(aH(i,:).*((x - pH(i,:)).^2)));

3. Function F20:
Function definition: function o = F20(x)
Calculation: Define aH = [10 3 17 3.5 1.7 8;.05 10 17 .1 8 14;3 3.5 1.7 10 17 8;17 8 .05 10 .1 14], cH = [1 1.2 3 3.2], pH = [.1312 .1696 .5569 .0124 .8283 .5886;.2329 .4135 .8307 .3736 .1004 .9991;.2348 .1415 .3522 .2883 .3047 .6650;.4047 .8828 .8732 .5743 .1091 .0381]. Initialize o = 0. Loop i from 1 to 4: o = o - cH(i)*exp(-(sum(aH(i,:).*((x - pH(i,:)).^2)));

4. Function F21:
Function definition: function o = F21(x)
Calculation: Define aSH = [4 4 4 4;1 1 1 1;8 8 8 8;6 6 6 6;3 7 3 7;2 9 2 9;5 5 3 3;8 1 8 1;6 2 6 2;7 3.6 7 3.6], cSH = [.1 .2 .2 .4 .4 .6 .3 .7 .5 .5]. Initialize o = 0. Loop i from 1 to 5: o = o - ((x - aSH(i,:))*(x - aSH(i,:))' + cSH(i))^(-1);

5. Function F22:
Function definition: function o = F22(x)
Calculation: Use the same aSH and cSH as F21. Initialize o = 0. Loop i from 1 to 7: o = o - ((x - aSH(i,:))*(x - aSH(i,:))' + cSH(i))^(-1);

6. Function F23:
Function definition: function o = F23(x)
Calculation: Use the same aSH and cSH as F21. Initialize o = 0. Loop i from 1 to 10: o = o - ((x - aSH(i,:))*(x - aSH(i,:))' + cSH(i))^(-1);

All variables (aH, cH, pH, aSH, cSH) must have the exact values provided. The loops, matrix operations, and arithmetic calculations must be executed exactly as described. Other functions called in the code are assumed to be pre-defined.
test_cases: clear; clc;
rng(42);
correct = 16649.063712;
x2 = [0.5, 1.2];  
x3 = [0.3, 0.7, 1.5]; 
x4 = [0.3, 0.7, 1.5, 2.1];
x6 = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2]; 
val = F18(x2) + F19(x3) + F20(x6) + F21(x4) + F22(x4) + F23(x4);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

correct = 17899.312189;
x2 = [0.6, 1.3];  
x3 = [0.5, 1.7, 1.2]; 
x4 = [0.1, 1.5, 1.6, 2.1];
x6 = [0.5, 0.2, 1.6, 0.8, 1.1, 1.2]; 
val = F18(x2) + F19(x3) + F20(x6) + F21(x4) + F22(x4) + F23(x4);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

correct = 42552.178761;
x2 = [0.2, 1.3];  
x3 = [1.3, 0.7, 1.3]; 
x4 = [2.2, 0.6, 1.2, 0.5];
x6 = [0.2, 0.1, 0.7, 0.2, 1.0, 1.1]; 
val = F18(x2) + F19(x3) + F20(x6) + F21(x4) + F22(x4) + F23(x4);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 5
step_description_prompt: Please use MATLAB code to generate a function named Get_Functions_details that, given an input string F, returns the corresponding lower bound (lb), upper bound (ub), dimension (dim), and function handle (fobj) based on the value of F. The function definition is function [lb,ub,dim,fobj] = Get_Functions_details(F). The algorithm flow is as follows: use a switch-case structure to match the input F. For each case:
- When F is 'F1', set fobj = @F1, lb = -100, ub = 100, dim = 10.
- When F is 'F2', set fobj = @F2, lb = -10, ub = 10, dim = 10.
- When F is 'F3', set fobj = @F3, lb = -100, ub = 100, dim = 10.
- When F is 'F4', set fobj = @F4, lb = -100, ub = 100, dim = 10.
- When F is 'F5', set fobj = @F5, lb = -30, ub = 30, dim = 10.
- When F is 'F6', set fobj = @F6, lb = -100, ub = 100, dim = 10.
- When F is 'F7', set fobj = @F7, lb = -1.28, ub = 1.28, dim = 10.
- When F is 'F8', set fobj = @F8, lb = -500, ub = 500, dim = 10.
- When F is 'F9', set fobj = @F9, lb = -5.12, ub = 5.12, dim = 10.
- When F is 'F10', set fobj = @F10, lb = -32, ub = 32, dim = 10.
- When F is 'F11', set fobj = @F11, lb = -600, ub = 600, dim = 10.
- When F is 'F12', set fobj = @F12, lb = -50, ub = 50, dim = 10.
- When F is 'F13', set fobj = @F13, lb = -50, ub = 50, dim = 10.
- When F is 'F14', set fobj = @F14, lb = -65.536, ub = 65.536, dim = 2.
- When F is 'F15', set fobj = @F15, lb = -5, ub = 5, dim = 4.
- When F is 'F16', set fobj = @F16, lb = -5, ub = 5, dim = 2.
- When F is 'F17', set fobj = @F17, lb = [-5,0], ub = [10,15], dim = 2.
- When F is 'F18', set fobj = @F18, lb = -2, ub = 2, dim = 2.
- When F is 'F19', set fobj = @F19, lb = 0, ub = 1, dim = 3.
- When F is 'F20', set fobj = @F20, lb = 0, ub = 1, dim = 6.
- When F is 'F21', set fobj = @F21, lb = 0, ub = 10, dim = 4.
- When F is 'F22', set fobj = @F22, lb = 0, ub = 10, dim = 4.
- When F is 'F23', set fobj = @F23, lb = 0, ub = 10, dim = 4.
The functions F1 to F23 called in the code are assumed to be already defined and do not need to be redefined. The function name must be identical to the given one.
function_header: function [lb,ub,dim,fobj] = Get_Functions_details(F)

end
test_cases: clear; clc;
rng(42);
test_funcs = {'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', ...
              'F11', 'F12', 'F13', 'F14', 'F15', 'F16', 'F17', 'F18', 'F19', ...
              'F20', 'F21', 'F22', 'F23'};
total = 0;
correct = 864.188863;
for i = 1:length(test_funcs)
    [lb, ub, dim, fobj] = Get_Functions_details(test_funcs{i});
    if isscalar(lb) && isscalar(ub)
        x = (lb + ub) / 2 * ones(1, dim);
    else
        x = (lb + ub) / 2;
    end
    fval = fobj(x);
    total = total + sum(lb(:)) + sum(ub(:)) + dim + fval;
end
tol = abs(total-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 6
step_description_prompt: Please write a MATLAB function named initialization that initializes the first population of search agents.
The function is defined as: function Positions = initialization(SearchAgents_no, dim, ub, lb)
Algorithm flow:
1. Compute Boundary_no as the number of columns in ub using size(ub, 2).
2. Check if Boundary_no equals 1 (indicating all variables have the same upper and lower bounds):
   a. If yes, create ub_new as a 1-by-dim vector where all elements are ub, and lb_new as a 1-by-dim vector where all elements are lb.
   b. If no, set ub_new equal to ub and lb_new equal to lb.
3. Iterate over each dimension i from 1 to dim:
   a. Extract ub_i as the i-th element of ub_new and lb_i as the i-th element of lb_new.
   b. Generate a SearchAgents_no-by-1 vector of uniformly distributed random numbers between 0 and 1 using rand(SearchAgents_no, 1), multiply it by (ub_i - lb_i), then add lb_i to get the i-th column of Positions.
4. Transpose the Positions matrix to convert it from a SearchAgents_no-by-dim matrix to a dim-by-SearchAgents_no matrix.
5. Return the Positions matrix.
Ensure the function strictly follows the above steps, uses the rand function (assumed predefined), and produces the exact output as the logic described.
function_header: function Positions=initialization(SearchAgents_no,dim,ub,lb)

end
test_cases: clear; clc;
rng(42);

correct = 85.422048;
X1 = initialization(5, 3, 10, -5);
X2 = initialization(4, 3, [5,10,15], [-2,0,3]);
X3 = initialization(3, 2, 0, 0);
val = sum(X1(:)) + sum(X2(:)) + sum(X3(:));
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

correct = 94.834255;
X1 = initialization(2, 5, 10, -7);
X2 = initialization(4, 3, [5,8,12], [-1,1,3]);
X3 = initialization(2, 2, 1, 4);
val = sum(X1(:)) + sum(X2(:)) + sum(X3(:));
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

correct = 59.955864;
X1 = initialization(6, 2, 8, -8);
X2 = initialization(4, 3, [2,10,12], [-2,2,6]);
X3 = initialization(3, 4, 0, 1);
val = sum(X1(:)) + sum(X2(:)) + sum(X3(:));
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 7
step_description_prompt: Please write a MATLAB function named distance that calculates the element-wise Euclidean distance between two vectors of the same length.
Function definition: function o = distance(a, b)
Algorithm flow: 1. Iterate i from 1 to the number of rows in a (size(a,1)). 2. For each i, compute the square root of the squared difference between a(i) and b(i), then assign the result to the i-th element of the first row of o (o(1,i)).
The input vectors a and b are assumed to have the same length. The output o is a row vector where each element corresponds to the element-wise Euclidean distance of a and b.
function_header: function o = distance(a,b)

end
test_cases: clear; clc;
rng(42);

d1 = distance([1;2;3], [4;5;6]);
d2 = distance([-1;2], [3;-4]);
d3 = distance([1.5;2.5], [0.5;3.5]);
val = sum(d1);
correct = 9.000000;
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
val = sum(d2);
correct = 10.000000;
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
val = sum(d3);
correct = 2.000000;
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 8
step_description_prompt: Please write a MATLAB function named Levy that generates a Levy flight step vector. The function is defined as function o=Levy(d), where d is the dimension of the step vector. Follow these steps: 1. Set beta = 3/2. 2. Calculate sigma using the formula (gamma(1+beta)*sin(pi*beta/2)/(gamma((1+beta)/2)*beta*2^((beta-1)/2)))^(1/beta). 3. Generate u as a 1-by-d random vector from the standard normal distribution scaled by sigma: u = randn(1, d) * sigma. 4. Generate v as a 1-by-d random vector from the standard normal distribution: v = randn(1, d). 5. Compute step as u divided by the absolute value of v raised to the power of 1/beta: step = u ./ abs(v) .^ (1/beta). 6. Scale step by 0.01 to get the output o: o = 0.01 * step. Functions gamma, randn are assumed to be pre-defined and do not need to be redefined.
function_header: function o=Levy(d)

end
test_cases: clear; clc;
rng(42);

o1 = Levy(1);
o2 = Levy(2);
o3 = Levy(5);

val = sum(o1);
correct = -0.00412278;
tol = abs((val-correct)/correct);
if tol>1e-3
    error('Wrong!')
end

val = sum(o2);
correct = 0.01043572;
tol = abs((val-correct)/correct);
if tol>1e-3
    error('Wrong!')
end

val = sum(o3);
correct = 0.00281551;
tol = abs((val-correct)/correct);
if tol>1e-3
    disp('Wrong!')
    fprintf("%.8f\n",tol)
    fprintf("%.8f\n",val)
end
disp('Completely right!')

step_number: 9
step_description_prompt: Write a MATLAB function named DA that implements the Dragonfly Algorithm for optimization, minimizing a given fitness function. The function returns the best fitness value, corresponding best position, and a convergence curve tracking the best fitness at each iteration. Strictly follow the algorithm flow, variable handling, and boundary conditions as described to ensure identical results to the original code. The functions initialization(), distance(), and Levy() are pre-defined and do not require reimplementation.

Function Definition:
[Best_score, Best_pos, cg_curve] = DA(SearchAgents_no, Max_iteration, lb, ub, dim, fobj)

Input Parameters:
- SearchAgents_no: Number of dragonfly agents (positive integer).
- Max_iteration: Maximum number of iterations (positive integer).
- lb: Lower bound of the search space (1-by-dim vector or scalar).
- ub: Upper bound of the search space (1-by-dim vector or scalar).
- dim: Dimension of the optimization problem (positive integer).
- fobj: Handle to the fitness function (accepts a 1-by-dim vector, returns a scalar).

Output Parameters:
- Best_score: Best (minimum) fitness value found (scalar).
- Best_pos: Best position vector corresponding to Best_score (dim-by-1 vector).
- cg_curve: Convergence curve (1-by-Max_iteration vector, tracks Best_score at each iteration).

Algorithm Flow:
1. Initialize cg_curve as a 1-by-Max_iteration zero vector.
2. If lb or ub are scalars (size(ub,2) == 1), expand them to 1-by-dim vectors using ones(1,dim)*lb and ones(1,dim)*ub.
3. Initialize variables:
   - r = (ub - lb) / 10; (neighborhood radius, matches ub/lb size).
   - Delta_max = (ub - lb) / 10; (maximum step size, matches ub/lb size).
   - Food_fitness = inf; (best food fitness, minimized).
   - Food_pos = zeros(dim, 1); (best food position).
   - Enemy_fitness = -inf; (worst enemy fitness, maximized).
   - Enemy_pos = zeros(dim, 1); (worst enemy position).
4. Generate initial positions (X, dim-by-SearchAgents_no) and step vectors (DeltaX, dim-by-SearchAgents_no) via initialization(SearchAgents_no, dim, ub, lb).
5. Initialize Fitness as a 1-by-SearchAgents_no zero vector.

6. For iter = 1 to Max_iteration:
   a. Update control parameters:
      - r = (ub - lb)/4 + (ub - lb) * (iter/Max_iteration)*2;
      - w = 0.9 - iter * (0.5 / Max_iteration); (inertia weight, 0.9→0.4).
      - my_c = 0.1 - iter * (0.1 / (Max_iteration/2)); (social coefficient, clamped ≥0).
      - s = 2 * rand() * my_c; (social interaction coefficient).
      - a = 2 * rand() * my_c; (alignment coefficient).
      - c = 2 * rand() * my_c; (cohesion coefficient).
      - f = 2 * rand(); (food attraction coefficient).
      - e = my_c; (enemy distraction coefficient).
   b. Evaluate fitness and update food/enemy:
      For each i = 1 to SearchAgents_no:
         i. Fitness(1,i) = fobj(X(:,i)'); (transpose X(:,i) to 1-by-dim for fobj).
         ii. If Fitness(1,i) < Food_fitness: Update Food_fitness = Fitness(1,i), Food_pos = X(:,i).
         iii. If Fitness(1,i) > Enemy_fitness && all(X(:,i) < ub') && all(X(:,i) > lb'): Update Enemy_fitness = Fitness(1,i), Enemy_pos = X(:,i).
   c. For each i = 1 to SearchAgents_no:
      i. Find neighbors: Collect j where distance(X(:,i), X(:,j)) ≤ r && distance(X(:,i), X(:,j)) ~= 0. Store neighbor step vectors in Neighbours_DeltaX (dim-by-neighbours_no) and positions in Neighbours_X (dim-by-neighbours_no). Count neighbours_no.
      ii. Compute social interaction (S): If neighbours_no > 1, S = -sum(Neighbours_X - X(:,i)*ones(1,neighbours_no), 2); else S = zeros(dim,1).
      iii. Compute alignment (A): If neighbours_no > 1, A = mean(Neighbours_DeltaX, 2); else A = DeltaX(:,i).
      iv. Compute cohesion (C): C_temp = (neighbours_no > 1) ? mean(Neighbours_X,2) : X(:,i); C = C_temp - X(:,i).
      v. Compute food vector (F): Dist2Food = distance(X(:,i), Food_pos); F = (all(Dist2Food ≤ r)) ? (Food_pos - X(:,i)) : zeros(dim,1).
      vi. Compute enemy vector (Enemy): Dist2Enemy = distance(X(:,i), Enemy_pos); Enemy = (all(Dist2Enemy ≤ r)) ? (Enemy_pos + X(:,i)) : zeros(dim,1).
      vii. First boundary check (element-wise):
           For tt = 1 to dim:
               If X(tt,i) > ub(tt): X(tt,i) = lb(tt); DeltaX(tt,i) = rand();
               If X(tt,i) < lb(tt): X(tt,i) = ub(tt); DeltaX(tt,i) = rand();
      viii. Update DeltaX/X using PREVIOUS Dist2Food:
           If any(Dist2Food > r): (Outside food neighborhood before boundary check)
               If neighbours_no > 1:
                   For j = 1 to dim:
                       DeltaX(j,i) = w*DeltaX(j,i) + rand()*A(j) + rand()*C(j) + rand()*S(j);
                       DeltaX(j,i) = clamp(DeltaX(j,i), -Delta_max(j), Delta_max(j));
                       X(j,i) = X(j,i) + DeltaX(j,i);
               Else: (No neighbors, use Levy flight)
                   X(:,i) = X(:,i) + Levy(dim)' .* X(:,i);
                   DeltaX(:,i) = 0;
           Else: (Inside food neighborhood before boundary check)
               For j = 1 to dim:
                   DeltaX(j,i) = (a*A(j) + c*C(j) + s*S(j) + f*F(j) + e*Enemy(j)) + w*DeltaX(j,i);
                   DeltaX(j,i) = clamp(DeltaX(j,i), -Delta_max(j), Delta_max(j));
                   X(j,i) = X(j,i) + DeltaX(j,i);
      ix. Second boundary check (vectorized):
           Flag4ub = X(:,i) > ub'; Flag4lb = X(:,i) < lb';
           X(:,i) = X(:,i) .* (~(Flag4ub+Flag4lb)) + ub'.*Flag4ub + lb'.*Flag4lb;
   d. Update outputs: Best_score = Food_fitness; Best_pos = Food_pos; cg_curve(iter) = Best_score;

Note: The clamp function restricts DeltaX(j,i) to [-Delta_max(j), Delta_max(j)]. The functions initialization(), distance(), and Levy() are pre-defined. All operations (element-wise, vector/matrix sizes) must match exactly. Boundary conditions and random number usage (separate rand() calls for each term) are critical for identical results.
function_header: function [Best_score,Best_pos,cg_curve]=DA(SearchAgents_no,Max_iteration,lb,ub,dim,fobj)

end
test_cases: clear; clc;
rng(42);

SearchAgents_no = 30;
Max_iteration = 5;
Function_name = 'F2';
[lb,ub,dim,fobj]=Get_Functions_details(Function_name);
[Best_score,Best_pos,cg_curve]=DA(SearchAgents_no,Max_iteration,lb,ub,dim,fobj);
val = Best_score + sum(Best_pos) + sum(cg_curve);
correct = 779.601851;
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

SearchAgents_no = 20;
Max_iteration = 10;
Function_name = 'F11';
[lb,ub,dim,fobj]=Get_Functions_details(Function_name);
[Best_score,Best_pos,cg_curve]=DA(SearchAgents_no,Max_iteration,lb,ub,dim,fobj);
val = Best_score + sum(Best_pos) + sum(cg_curve);
correct = 875.105794;
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

SearchAgents_no = 30;
Max_iteration = 6;
Function_name = 'F20';
[lb,ub,dim,fobj]=Get_Functions_details(Function_name);
[Best_score,Best_pos,cg_curve]=DA(SearchAgents_no,Max_iteration,lb,ub,dim,fobj);
val = Best_score + sum(Best_pos) + sum(cg_curve);
correct = -7.213389;
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 10
step_description_prompt: Please write a MATLAB function named func_plot that draws the 3D surface plot of benchmark functions.
function func_plot(func_name)
1. Call Get_Functions_details(func_name) to obtain lb, ub, dim, fobj (this function is assumed to be pre-defined).
2. Use a switch-case structure to set the range and step of x and y based on func_name:
   - Case 'F1' to 'F4', 'F6', 'F14': x = -100:2:100; y = x;
   - Case 'F5', 'F11': x = -500:10:500; y = x;
   - Case 'F7': x = -1:0.03:1; y = x;
   - Case 'F8': x = -500:10:500; y = x;
   - Case 'F9', 'F15', 'F17', 'F19'-'F23': x = -5:0.1:5; y = x;
   - Case 'F10': x = -20:0.5:20; y = x;
   - Case 'F12': x = -10:0.1:10; y = x;
   - Case 'F13': x = -5:0.08:5; y = x;
   - Case 'F16': x = -1:0.01:1; y = x;
   - Case 'F18': x = -5:0.06:5; y = x;
3. Compute L as the length of x.
4. Initialize an empty matrix f.
5. Use nested loops (i from 1 to L, j from 1 to L) to calculate f(i,j):
   - If func_name is not 'F15','F19','F20','F21','F22','F23', set f(i,j) = fobj([x(i), y(j)]).
   - If func_name is 'F15', set f(i,j) = fobj([x(i), y(j), 0, 0]).
   - If func_name is 'F19', set f(i,j) = fobj([x(i), y(j), 0]).
   - If func_name is 'F20', set f(i,j) = fobj([x(i), y(j), 0, 0, 0, 0]).
   - If func_name is 'F21','F22','F23', set f(i,j) = fobj([x(i), y(j), 0, 0]).
6. Plot the 3D surface with surfc(x, y, f, 'LineStyle', 'none').
ground_truth_code: % This function draws the benchmark functions
function func_plot(func_name)
[lb,ub,dim,fobj]=Get_Functions_details(func_name);
switch func_name 
    case 'F1' 
        x=-100:2:100; y=x;
    case 'F2' 
        x=-100:2:100; y=x;
    case 'F3' 
        x=-100:2:100; y=x;
    case 'F4' 
        x=-100:2:100; y=x;
    case 'F5' 
        x=-200:2:200; y=x;
    case 'F6' 
        x=-100:2:100; y=x;
    case 'F7' 
        x=-1:0.03:1;  y=x;
    case 'F8' 
        x=-500:10:500;y=x;
    case 'F9' 
        x=-5:0.1:5;   y=x;  
    case 'F10' 
        x=-20:0.5:20; y=x;
    case 'F11' 
        x=-500:10:500; y=x;
    case 'F12' 
        x=-10:0.1:10; y=x;
    case 'F13' 
        x=-5:0.08:5; y=x;
    case 'F14' 
        x=-100:2:100; y=x;
    case 'F15' 
        x=-5:0.1:5; y=x;
    case 'F16' 
        x=-1:0.01:1; y=x;
    case 'F17' 
        x=-5:0.1:5; y=x;
    case 'F18' 
        x=-5:0.06:5; y=x;
    case 'F19' 
        x=-5:0.1:5; y=x;
    case 'F20' 
        x=-5:0.1:5; y=x;      
    case 'F21' 
        x=-5:0.1:5; y=x;
    case 'F22' 
        x=-5:0.1:5; y=x;   
    case 'F23' 
        x=-5:0.1:5; y=x;
end    
L=length(x);
f=[];
for i=1:L
    for j=1:L
        if strcmp(func_name,'F15')==0 && strcmp(func_name,'F19')==0 && strcmp(func_name,'F20')==0 && strcmp(func_name,'F21')==0 && strcmp(func_name,'F22')==0 && strcmp(func_name,'F23')==0
            f(i,j)=fobj([x(i),y(j)]);
        end
        if strcmp(func_name,'F15')==1
            f(i,j)=fobj([x(i),y(j),0,0]);
        end
        if strcmp(func_name,'F19')==1
            f(i,j)=fobj([x(i),y(j),0]);
        end
        if strcmp(func_name,'F20')==1
            f(i,j)=fobj([x(i),y(j),0,0,0,0]);
        end       
        if strcmp(func_name,'F21')==1 || strcmp(func_name,'F22')==1 ||strcmp(func_name,'F23')==1
            f(i,j)=fobj([x(i),y(j),0,0]);
        end          
    end
end
surfc(x,y,f,'LineStyle','none');
end
function_header: function func_plot(func_name)

end

step_number: 11
step_description_prompt: Please use MATLAB code to create a script that implements running the Dragonfly Algorithm (DA) on a selected benchmark function, including parameter setup, calling pre-defined functions, plotting results, and displaying the best solution and optimal value. The script should follow these steps:

1. Clear the workspace and command window, then set the random seed to 42 using `rng(42)`.
2. Define `SearchAgents_no = 40` (number of search agents), `Function_name = 'F1'` (test function name from F1 to F23), and `Max_iteration = 500` (maximum iterations).
3. Obtain test function details by calling `[lb, ub, dim, fobj] = Get_Functions_details(Function_name)` (this function is pre-defined and does not need redefinition).
4. Run the DA algorithm by calling `[Best_score, Best_pos, cg_curve] = DA(SearchAgents_no, Max_iteration, lb, ub, dim, fobj)` (this function is pre-defined and does not need redefinition).
5. Create a figure with `figure('Position',[400 400 560 190])`.
6. For the first subplot (`subplot(1,2,1)`):
   - Call `func_plot(Function_name)` (pre-defined) to draw the test function.
   - Set title to `'Test function'`, x-label to `'x_1'`, y-label to `'x_2'`, z-label to `[Function_name,'( x_1 , x_2 )']`.
   - Turn off the grid with `grid off`.
7. For the second subplot (`subplot(1,2,2)`):
   - Plot the convergence curve using `semilogy(cg_curve,'Color','r')`.
   - Set title to `'Convergence curve'`, x-label to `'Iteration'`, y-label to `'Best score obtained so far'`.
   - Adjust axes with `axis tight`, turn off the grid with `grid off`, enable box with `box on`, and add legend `'DA'` using `legend('DA')`.
8. Display the best solution with `display(['The best solution obtained by DA is : ', num2str(Best_pos')])`.
9. Display the best optimal value with `display(['The best optimal value of the objective funciton found by DA is : ', num2str(Best_score)])`.

The functions `Get_Functions_details`, `DA`, and `func_plot` are assumed to be pre-defined and do not need to be reimplemented. Ensure all variable names, parameters, plot settings, and display messages are exactly the same as specified.
test_cases: rng(42)
correct_score = 0.16859407;
correct_pos = 0.37887071;
val_score = sum(Best_score(:));
val_pos = sum(Best_pos(:));
tol_score = abs(val_score-correct_score);
if tol_score > 1e-4
    error('Wrong')
end
tol_pos = abs(val_pos-correct_pos);
if tol_pos > 1e-4
    error('Wrong')
end
disp('Completely right!')

General solution:

General tests: