Avoiding too many figures from loop in GA Toolbox

1 回表示 (過去 30 日間)
cniv_we
cniv_we 2017 年 10 月 12 日
コメント済み: OCDER 2017 年 10 月 13 日
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.

採用された回答

OCDER
OCDER 2017 年 10 月 12 日
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 件のコメント
cniv_we
cniv_we 2017 年 10 月 13 日
Thanks!
OCDER
OCDER 2017 年 10 月 13 日
You're welcome!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGenetic Algorithm についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by