필터 지우기
필터 지우기

Switch statement not recognizing a valid input

조회 수: 5 (최근 30일)
James Dossett
James Dossett 2016년 2월 26일
댓글: Jan 2016년 2월 28일
I'm making a GUI and it has this code:
% --- Executes on selection change in AverageItem.
function AverageItem_Callback(hObject, eventdata, handles)
% hObject handle to AverageItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%
% Hints: contents = cellstr(get(hObject,'String')) returns AverageItem contents as cell array
% contents{get(hObject,'Value')} returns selected item from AverageItem
% Determine the selected data set.
str = get(hObject, 'String');
val = get(hObject,'Value');
% Set current data to the selected data set.
switch str{val};
case 'Phase (Degrees)' % User selects Phase (Degrees)
AverageItem = 1;
case 'Magnitude (V/m)' % User selects Magnitude (V/m)
AverageItem = 2;
case 'RCS (dBsm)' % User selects RCS (dBsm)
AverageItem = 3;
otherwise
error(['Unknown Choice: ' str{val}])
end
% Save the data to the workspace
assignin('base','AverageItem',AverageItem);
The problem is, whenever I choose 'RCS (dBsm)' in the GUI, it does not set AverageItem = 3. It just displays the 'Unknown Choice:' error. Any ideas? Phase and Magnitude work just fine. Thanks!

채택된 답변

Titus Edelhofer
Titus Edelhofer 2016년 2월 26일
Hi,
it must be then that the two strings are not equal. Put a breakpoint before the switch and compare str{val} with 'RCS (dBsm)'. Sometimes it helps to convert to doubles (i.e. ascii numbers) to see the difference.
double('RCS (dBsm)')
ans =
82 67 83 32 40 100 66 115 109 41
A tab might look like one space for example.
Titus
  댓글 수: 3
Titus Edelhofer
Titus Edelhofer 2016년 2월 28일
:)
Jan
Jan 2016년 2월 28일
To catch similar problems I add delimiters to the error messages:
error('Unknown Choice: [%s]', str{val})
This shows trailing spaces and does not fail in case of escape characters inside the string. The output of ['Unknown Choice: ' str] is undefined, if str contains e.g. '%s' and the output is unexpected, when control characters like \t, \n or the backspace \b are included.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by