模拟退火算法 matlab 代码
时间: 2023-10-05 18:08:02 浏览: 92
Sure, here is an example of a simulated annealing algorithm implemented in MATLAB:
```matlab
% Objective function
fun = @(x) x^2;
% Simulated Annealing parameters
initialTemp = 100; % Initial temperature
finalTemp = 0.01; % Final temperature
maxIterations = 1000; % Maximum number of iterations
alpha = 0.95; % Cooling rate
% Initialize
bestSolution = rand(); % Initial solution
bestCost = fun(bestSolution); % Initial cost
% Main loop
for iter = 1:maxIterations
currentTemp = initialTemp * alpha^(iter-1);
% Generate a new solution
newSolution = bestSolution + randn()*currentTemp;
newCost = fun(newSolution);
% Accept or reject the new solution based on the cost difference and the current temperature
if newCost < bestCost || exp((bestCost - newCost) / currentTemp) > rand()
bestSolution = newSolution;
bestCost = newCost;
end
end
disp(['Best solution: ' num2str(bestSolution)]);
disp(['Best cost: ' num2str(bestCost)]);
```
In this example, the objective function is defined as `x^2`. You can modify this function according to your problem. The simulated annealing parameters such as initial and final temperature, maximum iterations, and cooling rate can also be adjusted based on your specific requirements.
This code will iteratively update the solution by generating a new solution and accepting or rejecting it based on the cost difference and the current temperature. The algorithm aims to find the solution that minimizes the objective function. The best solution and its corresponding cost are displayed at the end.
Please note that this is a basic implementation and may need further customization depending on your specific problem.
阅读全文