MATLAB: How to use toogle button to switch on and off a push button

guiMATLABon and offpushbuttontoggle buttontoggle switch

when i push the toggle button, it displays on and off but I want that when I pressed the toggle switch to on, the "add" pushbutton will execute. I'm thinking of adding a while loop to the code of "add" button but i dont know how. I want my add button executes only when the toggle button is on.
here's my code:
% --- Executes on button press in add.
function add_Callback(hObject, eventdata, handles)
% hObject handle to add (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA);
persistent add
count=handles.count;
if isempty(add)
add=count;
add=add+1;
else
add=add+1;
end
handles.add=add;
set(handles.screen,'String',add);
guidata(hObject, handles);
% --- Executes on button press in on_offbutton.
function on_offbutton_Callback(hObject, eventdata, handles)
% hObject handle to on_offbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of on_offbutton
button_state = get(hObject,'Value');
if(button_state == 1)
set(handles.on_offbutton,'String','ON','ForegroundColor','green')
else
set(handles.on_offbutton,'string','OFF','foregroundcolor','red')
end

Best Answer

If I understand correctly, you have a toggle button and a pushbutton. When you set the toggle button to 'on', you want the pushbutton callback to execute. Is that correct?
If that is correct, the trick is perhaps to realize that your callbacks are just functions. You can call them just like any function. The solution here is to call the pushbutton callback from within the toggle callback function (when value is 'on'). Just be sure to set the first input to be the corresponding component object instead of hObject.
% --- Executes on button press in on_offbutton.
function on_offbutton_Callback(hObject, eventdata, handles)
% hObject handle to on_offbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of on_offbutton
button_state = get(hObject,'Value');
if(button_state == 1)
set(handles.on_offbutton,'String','ON','ForegroundColor','green')
% Call the add callback function.
add_Callback(handles.add_callback, eventdata, handles)
else
set(handles.on_offbutton,'string','OFF','foregroundcolor','red')
end