Switch statement not recognizing a valid input

5 次查看(过去 30 天)
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 个评论
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