Avoiding too many figures from loop in GA Toolbox

1 vue (au cours des 30 derniers jours)
cniv_we
cniv_we le 12 Oct 2017
Commenté : OCDER le 13 Oct 2017
I am creating a function which looks like this:
function F = fitnessfun(x)
...
score = x1+x2+x3
...
figure('Color',[1 1 1],'position', [500, 250, 640, 480]);
imagesc(score);
title(['Score: ', num2str(score)],'Fontsize',24);
Now, when I run this function in Genetic Algorithm toolbox, i.e. I call @fitnessfun from the Optimtoolbox, everything runs smoothly, except the script making a new figure window for each GA generation. Tried to prevent this by using classical trick:
figure('Color',[1 1 1],'position', [500, 250, 640, 480]);
hold on
imagesc(score);
title(['Score: ', num2str(score)],'Fontsize',24);
hold off
But that does NOT help, new figure windows are created until termination (e.g. 500th generation) and causing my PC to crash.
Any solution to close the figure window automatically everytime a new figure is opened?
Thanks in advance.

Réponse acceptée

OCDER
OCDER le 12 Oct 2017
One way to do this is to create a template figure, and then pass this to your function to prevent creating/closing a new figure every time (which is slow, especially when doing 500+ iterations).
function F = fitnessfun(x, varargin)
...
score = x1+x2+x3
...
%If you already have a figure, just modify what you need
if ~isempty(varargin) && isa(varargin{1}, 'matlab.ui.Figure')
Gx = varargin{1}; % figure handle
Im = findobj(Gx, 'type', 'image'); % image handle
Ax = findobj(Gx, 'type', 'axes'); % axes handle
if ~isempty(Im) && ~isempty(Ax)
Im.CData = score;
title(Ax, ['Score: ', num2str(score)], 'Fontsize', 24);
return
end
end
%Otherwise, create a whole new figure
figure('Color',[1 1 1],'position', [500, 250, 640, 480]);
imagesc(score);
title(['Score: ', num2str(score)],'Fontsize',24);
Summon your function as this
for j = 1:1000
if j == 1
F = fitnessfun(x(j)) %Start a template figure the first time,
else
F = fitnessfun(x(j), gcf) %Pass on current figure handle to your function
end
end
  2 commentaires
cniv_we
cniv_we le 13 Oct 2017
Thanks!
OCDER
OCDER le 13 Oct 2017
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (0)

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by