MATLAB: Axes(handles.axes1) doesn’t work in localEventListener function in GUI

axesguihandlesMATLABsimulink

Hi everybody I made a simulink system (Vessel) and use GUI for visualization of this. The GUI contains an axes and a pushbutton. When pushbutton is pressed program load 'Vessel' and start simulation. I added "add_exec_event_listener" to get output parameter of Gain block and plot it in GUI axes. But the problem is when I run mfile this error appears referring to axes(handles.axes1) in localEventListener function: Undefined variable "handles" or class "handles.axes1". Could you help me please? Here is code for pushbutton:
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)figure(2)
global new_time new_temp
new_time=[];
new_temp=[];
ModelName = 'Vessel';
% Opens the Simulink model
open_system(ModelName);
% Simulink may optimise your model by integrating all your blocks. To
% prevent this, you need to disable the Block Reduction in the Optimisation
% settings.
set_param(ModelName,'BlockReduction','off');
% When the model starts, call the localAddEventListener function
set_param(ModelName,'StartFcn','localAddEventListener');
% Start the model
set_param(ModelName, 'SimulationCommand', 'start');
% When simulation starts, Simulink will call this function in order to
% register the event listener to the block 'SineWave'. The function
% localEventListener will execute everytime after the block 'SineWave' has
% returned its output.
function eventhandle = localAddEventListener
eventhandle = add_exec_event_listener('Vessel/Temp/Gain1', ...
'PostOutputs', @localEventListener);
% The function to be called when event is registered.
function localEventListener(block, eventdata)
% Gets the time and output value
global new_time new_temp
time = block.CurrentTime;
temp = block.OutputPort(1).Data;
new_time=[new_time,time];
new_temp=[new_temp,temp];
axes(handles.axes1)
plot(new_time,new_temp)

Best Answer

handles contains the handles to the user interface and need to be passed in explicitly to the callback. When you register the listener, rather than using strings, use anonymous functions which can capture the workspace variables, in this case handles.
% When the model starts, call the localAddEventListener function
set_param(ModelName,'StartFcn',@()localAddEventListener(handles));
And
function eventhandle = localAddEventListener(handles)
eventhandle = add_exec_event_listener('Vessel/Temp/Gain1', ...
'PostOutputs', @(src,evt)localEventListener(src,evt,handles));
Then add handles to the localEventListener signature too:
% The function to be called when event is registered.
function localEventListener(block, eventdata,handles)
Related Question