Switch statement not recognizing a valid input
2 ビュー (過去 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!
0 件のコメント
採用された回答
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
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 Center および File Exchange で Graphics Object Programming についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!