everyone. Probably, I am making a utterly silly mistake here but here is the problem:
I have made a GUI using MATLAB GUIDE. I added some checkboxes to the GUI so that they will plot something on axes2 if checked and delete it otherwise. In case if you ask, there are going to be other plots so there is hold on and off. It works like this:
function checkbox1_Callback(hObject, eventdata, handles)
% Hint: get(hObject,'Value') returns toggle state of checkbox1
if get(hObject, 'Value') == 1
axes(handles.axes2);
x = handles.x;
distanceX_Plot = evalin('base', 'CAN2_MPC_C19_Dist_X_VehObj0_Cval_MPC');
hold on;
distanceX_Plotted = plot(x,distanceX_Plot, 'r');
legend('Distance X')
hold off;
else
delete(distanceX_Plotted);
end
but the distanceX_Plotted in the IF part gets underlined and says variable might be unused and the second distanceX_Plotted in the ELSE statement says that variable may be used before it is defined.
The complete error is like this:
Undefined function or variable 'distanceX_Plotted'.
Error in untitled>checkbox1_Callback (line 224) delete(distanceX_Plotted);
Error in gui_mainfcn (line 95) feval(varargin{:});
Error in untitled (line 42) gui_mainfcn(gui_State, varargin{:});
Error in matlab.graphics.internal.figfile.FigFile/read>@(hObject,eventdata)untitled('checkbox1_Callback',hObject,eventdata,guidata(hObject)) Error while evaluating UIControl Callback
Thanks for any help.
Your current function will:
Create a set of axis and plot data. This plot is accessible with the handle distanceX_Plotted
.
Attempt to delete distanceX_Plotted
, which does not exist since it didn't enter the first part of the if-else block.
If you want to plot something on the axis handle.axis2
or delete it, you need to plot in the wanted axis, or delete the axis (and not the plot):
function checkbox1_Callback(hObject, eventdata, handles)
% Hint: get(hObject,'Value') returns toggle state of checkbox1
if get(hObject, 'Value') == 1
x = handles.x;
distanceX_Plot = evalin('base', 'CAN2_MPC_C19_Dist_X_VehObj0_Cval_MPC');
hold on;
distanceX_Plotted = plot(x,distanceX_Plot, 'r','Parent', handles.axes2); % modified
legend('Distance X')
hold off;
else
delete(handles.axes2); % modified
end
EDIT: If you would like to remove the last line you have plotted, write this in else
block:
if ~isempty(handles.axes2.Children)
delete(handles.axes2.Children(end));
end
It will remove the last line you printed on axes2
.