Switch statement not recognizing a valid input
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
James Dossett
am 26 Feb. 2016
Kommentiert: Jan
am 28 Feb. 2016
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 Kommentare
Akzeptierte Antwort
Titus Edelhofer
am 26 Feb. 2016
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 Kommentare
Jan
am 28 Feb. 2016
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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Graphics Object Programming finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!