模拟退火算法的matlab代码
时间: 2024-04-14 21:24:50 浏览: 16
模拟退火算法(Simulated Annealing)是一种全优化算法,用于在搜索空间中寻找最优解。下面是一个简单的模拟退火算法的MATLAB代码示例:
```matlab
% 目标函数
function y = objective(x)
y = x^2; % 这里以求解最小值为例,目标函数为x的平方
end
% 模拟退火算法
function [x_best, f_best] = simulated_annealing()
% 初始温度和终止温度
T_initial = 100;
T_final = 0.1;
% 初始解
x_current = rand(); % 随机生成一个初始解
f_current = objective(x_current); % 计算初始解的目标函数值
% 最优解
x_best = x_current;
f_best = f_current;
% 迭代次数和降温率
max_iterations = 1000;
cooling_rate = 0.95;
% 迭代搜索
for i = 1:max_iterations
% 生成新解
x_new = x_current + randn() * T_initial;
f_new = objective(x_new);
% 判断是否接受新解
if f_new < f_current || exp((f_current - f_new) / T_initial) > rand()
x_current = x_new;
f_current = f_new;
end
% 更新最优解
if f_current < f_best
x_best = x_current;
f_best = f_current;
end
% 降温
T_initial = T_initial * cooling_rate;
% 判断是否达到终止温度
if T_initial < T_final
break;
end
end
end
% 调用模拟退火算法求解最优解
[x_best, f_best] = simulated_annealing();
disp(['最优解:', num2str(x_best)]);
disp(['最优值:', num2str(f_best)]);
```