pushbutton to change the button string and function

1 次查看(过去 30 天)
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);

采纳的回答

Walter Roberson
Walter Roberson 2018-2-7
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 个评论
Walter Roberson
Walter Roberson 2018-2-7
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by