Switch statement not recognizing a valid input
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
James Dossett
el 26 de Feb. de 2016
Comentada: Jan
el 28 de Feb. de 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 comentarios
Respuesta aceptada
Titus Edelhofer
el 26 de Feb. de 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 comentarios
Jan
el 28 de Feb. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Graphics Object Programming en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!