MATLAB: Getting error in the OuputFcn for Genetic Algorithm

gaoutputfcnstate variable

Hi
I'm trying to save the state information by using an OutputFcn, but I keep getting errors when I call state.Generation. The errors only say
"Error in run_ga_search>myOutFun (line 63)
state.Generation"
Here's my OutputFcn code:
opts = gaoptimset('Display','off','OutputFcn',@myOutFun);
[x,fval,exitFlag,Output,population] = ga(@grating_cost_function_from_dc,nvars,[],[],[],[],LB,UB,[],opts);
function [state, options, optchanged] = myOutFun(options, state, flag)
%gen = state.Generation;
state.Generation
if strcmp(flag,'iter')
fileID = fopen([folder '/stoppingCriteria.txt'],'w');
fprintf(fileID, 'Stopping Criteria\n');
fprintf(fileID, 'Generation: %6.6f\n', state.Generation/options.MaxGenerations);
fprintf(fileID, 'Time: %6.6f\n', toc(state.StartTime)/options.MaxTime);
fprintf(fileID, 'StallG: %6.6f\n', (gen-state.LastImprovement)/options.MaxStallGenerations);
fprintf(fileID, 'StallT: %6.6f\n', toc(state.LastImprovementTime)/options.MaxStallTime);
fclose(fileID);
save([state_folder '/state_' num2str(state.Generation) '.mat'],'state');
end
end
Thanks

Best Answer

I figured out the problem. I only had code in my OuputFcn for one instance, i.e when the flag was iter so the outputfcn didn't know what to do when the flag was set to any other flag.