MATLAB Answers

0

pushbutton to change the button string and function

Asked by Huayan Wang on 7 Feb 2018
Latest activity Commented on by Huayan Wang on 7 Feb 2018
I am using the GUI to make an image acquisition application.
I use a pushbutton to control the camera on and off. The initial string of the pushbutton was set to 'Connect' I can click it and make the camera work and the button string change to 'Disconnect'. But if I click it again, it will give me errors and the camera does not stop. The string doesn't change back to 'Connect'.
(errors:Matrix dimensions must agree.
Error in Image2DSnap>pushbutton1_Callback (line 87) if (handles.pushbutton1.String == 'Connect')
Error in gui_mainfcn (line 95) feval(varargin{:});
Error in Image2DSnap (line 42) gui_mainfcn(gui_State, varargin{:});
Error in matlab.graphics.internal.figfile.FigFile/read>@(hObject,eventdata)Image2DSnap('pushbutton1_Callback',hObject,eventdata,guidata(hObject)) Error while evaluating UIControl Callback.)
Anybody can give me a hint?
Below is the relevant code:
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)
if (handles.pushbutton1.String == 'Connect')
vid = videoinput('gentl', 1);
vidRes = get(vid, 'VideoResolution');
hImage = image(zeros(vidRes(2), vidRes(1)), 'Parent', handles.Video);
preview(vid, hImage);
handles.pushbutton1.String = 'Disconnect';
% set(handles.pushbutton1,'string','Streaming','enable','off');
else
handles.pushbutton1.String = 'Connect';
closepreview
end
guidata(hObject, handles);

  0 Comments

Sign in to comment.

1 Answer

Answer by Walter Roberson
on 7 Feb 2018
 Accepted Answer

If you are using R2017a or later, you can change 'Connect' to "Connect" (and 'Disconnect' to "Disconnect" later in the code) without any other changes.
If you are using R2016b or earlier, then change
handles.pushbutton1.String == 'Connect'
to
strcmp(handles.pushbutton1.String, 'Connect')
The issue here is that you are working with char vectors and attempting to use the element-by-element comparison operator == but your two character vectors are not always the same length. strcmp() is the proper operator to compare two character vectors to determine if they are the same.

  3 Comments

The strcmp totally works! Thank you so much!
I am using R2017b. I did not quite understand your first solution.
Could you explain more?
Thank you!
if (handles.pushbutton1.String == 'Connect')
is the line you have now. With R2017a or later you can change that to
if (handles.pushbutton1.String == "Connect")
This makes use of an object of string type instead of using a char vector. The == operator is defined for string type and is effectively strcmp for this purpose.
Thank you!
Your explanation is very clear!

Sign in to comment.