Simulated annealing how to solve this error
Show older comments
Dear,
I have a ploblem using Global optimization toolbox with simulannealbnd.
I would be very grateful if anyone knows how to solve it.
the code of my programe is and the matrix of stars is in .txt file:
function prog
clc; close all;
global xc yc zc N
global bestfval_log
% load star positions from 'stars.txt'
stars = importdata('stars.txt');
N = size(stars.data, 1);
xc = stars.data(:,1); yc = stars.data(:,2); zc = stars.data(:,3);
names = stars.rowheaders;
plot_stars(xc, yc, zc, names);
bestfval_log = [];
% set up schedule, and plot it
schedule = 1:N;
disp('Initial Schedule:')
disp(schedule);
plot_schedule(schedule);
title(sprintf('Initial Schedule: %s \n Distance = %f light year', ...
num2str(schedule), cost_function(schedule)))
rotate3d
disp('Initial Total Distance:')
disp(cost_function(schedule));
pause
% set up options and call simulated annealing
rotate3d;
[schedule,fval,exitFlag,output] = ...
simulannealbnd(@cost_function, schedule, [], []); %#ok<*NASGU>
end
function d = cost_function(schedule)
global xc yc zc N
d = 0;
for i = 1:N-1
d = d + ( ( xc(schedule(i)) - xc(schedule(i+1)) )^2 ...
+ ( yc(schedule(i)) - yc(schedule(i+1)) )^2 ...
+ ( zc(schedule(i)) - zc(schedule(i+1)) )^2) ^.5 ;
end
i = N;
d = d + ( ( xc(schedule(i)) - xc(schedule(1)) )^2 ...
+ ( yc(schedule(i)) - yc(schedule(1)) )^2 ...
+ ( zc(schedule(i)) - zc(schedule(1)) )^2) ^.5 ;
end
function plot_stars(xc, yc, zc, names)
N = numel(xc);
f = figure('NumberTitle', 'off', ...
'Name', 'Galactic Traveling Salesman Problem');
ax = axes('Color', [0 0 0]);
hold on;
textargs = {'VerticalAlignment', 'top', ...
'HorizontalAlignment', 'center', ...
'FontName', 'Gill Sans MT'};
plot3(xc(1), yc(1), zc(1), 'y*');
text(xc(1), yc(1), zc(1)-.5, names{1}, textargs{:}, 'Color', 'y');
for i = 2:N
plot3(xc(i), yc(i), zc(i), 'w*');
text(xc(i), yc(i), zc(i)-.5, names{i}, textargs{:}, 'Color', 'w');
end
view(3); rotate3d;
end
function plot_schedule(schedule)
global xc yc zc
persistent l
if isempty(l) || ~ishghandle(l); l = plot3(0,0,0,'b-'); rotate3d; end
set(l, ...
'XData', [xc(schedule); xc(schedule(1))], ...
'YData', [yc(schedule); yc(schedule(1))], ...
'ZData', [zc(schedule); zc(schedule(1))] );
title(sprintf('Best schedule found so far: %s \n Distance = %f light year', ...
num2str(schedule), cost_function(schedule)))
end
1 Comment
Alan Weiss
on 28 May 2015
What is your question? What is the problem? Please explain, don't just throw up a bunch of uncommented code.
And you would do well to format your code with the {} Code button so that we could read it more easily.
Alan Weiss
MATLAB mathematical toolbox documentation
Accepted Answer
More Answers (0)
Categories
Find more on Simulated Annealing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!