MATLAB Answers

How to save data from Genetic Algorithm in case MATLAB crashes?

38 views (last 30 days)
Syahmeer How
Syahmeer How on 16 Dec 2019
Edited: Star Strider on 18 Dec 2019
Hi there,
I'm using the GA to find input parameters for my model. My fitness function is computationally expensive and takes about 2 days. In situation if MATLAB unexpectedly crashes, is there a way to save the data?
I have used the 'OutputFcn' option however this seems to save the data once my MATLAB finish the simulation. I purposely stop MATLAB and re-open it but can't seem to access the saved data.
If anyone have any useful tips to save simulation data while the simulation is running so I can access in case it crashes, I would be very grateful.
Many thanks,
Syahmeer How
Syahmeer How on 16 Dec 2019
@starstrider Thank you so much :) I look forward to hearing back from you

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 17 Dec 2019
It took a bit of trial and error, however this appears to work:
function [state,options,changed] = SaveOut(options,state,flag)
file_name = 'SaveBest.mat'; % Name File
if strcmp(flag,'iter')
ibest = state.Best(end);
ibest = find(state.Score == ibest,1,'last');
bestx = state.Population(ibest,:);
previous = load('SaveBest.mat');
var = [previous.var; bestx]; % Read Previous Results, Append New Value
save(file_name, 'var') % Write ‘Best Individual’ To File
changed = true; % Necessary For Code, Use Appropriate Value
It reads the existing saved values of ‘var’, appends the new value to the end of the matrix, then writes the new matrix to the .mat file.
It never occurred to me that this was even possible! I will use it in my longer optimisations from now on.
Star Strider
Star Strider on 17 Dec 2019
As always, my pleasure!
The ‘var’ field in my code would be the InitialPopulationMatrix (or at least part of it). The rest of your optimoptions structure would be as it was previously. The ga funciton will reconstitute everything else it need in the first iteration.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!