MATLAB: Saving/Loading the SimState Programmatically

saving loading simstate

I have a problem with saving/loading SimState programmatically. It works when i do it manually in the Simulink settings, but when doing it in a m file i get an error. My code is simply
simfile = 'simfile';
set_param(simfile, 'SaveFinalState', 'on', 'FinalStateName','SimState','SaveCompleteFinalSimState', 'on');
set_param(simfile, 'LoadInitialState', 'off');
simOut = sim(simfile,'StopTime',num2str(10));
set_param(simfile, 'SaveFinalState', 'off');
set_param(simfile, 'LoadInitialState', 'on', 'InitialState','SimState');
simOut = sim(simfile,'StopTime',num2str(20));
resulting in an error
??? Error using ==> simtest at 10
Error evaluating expression 'SimState' for 'Initial state' specified in the Configuration Parameters dialog for block diagram 'simfile': Undefined function or variable
'SimState'.
What am i missing?
Thanks 🙂
Benjamin

Best Answer

Thanks for quick response :)
I changed the code into simOut = sim(simfile,'StopTime',num2str(10),'SaveFinalState','on','FinalStateName','SimState','SaveCompleteFinalSimState', 'on'); simOut = sim(simfile,'StopTime',num2str(20),'SaveFinalState', 'off','LoadInitialState', 'on', 'InitialState','SimState');
which works. I didn't get your answer though. I thought the string you questioned, made that the mdl file called 'simfile.mdl' save the final values under the name 'SimState'. And these states are then loaded later. What am i misunderstanding?
Thanks again :)