Why is MATLAB not recognizing my variables in my switch block?

3 visualizaciones (últimos 30 días)
Kamryn Hall
Kamryn Hall el 26 de Nov. de 2021
Comentada: Kamryn Hall el 27 de Nov. de 2021
elseif typeRec == 3 %Option if the user wants regional options to choose from
fprintf('For regions we have:\n')
fprintf('1. American\n2. Italian\n3. Mexican\n4. Israeli\n')
region = input('Which one would you like to review? ', 's');
while isempty(region)
region = input('Which one would you like to review? ', 's');
end
switch region
case 1
regionc = 'American';
case 2
regionc = 'Italian';
case 3
regionc = 'Mexican';
case 4
regionc = 'Israeli';
end
for k=1:size(recipe,1)
if strcmp(recipe{k,6},regionc)
fprintf('%s\n', cell2mat(recipe(k,1)))
end
end
I'm not entirely sure what happened here. I have an Excel file with various recipes, and I am trying to print them. The switch block worked before, but the error 'Unrecognized function or variable 'regionc' ' pops up. Any help would be appreicated !

Respuestas (1)

Steven Lord
Steven Lord el 26 de Nov. de 2021
First, you probably want to have an otherwise block in your switch / case to handle the case where a user enters something other than 1, 2, 3, or 4.
Second, even if your user enters 1, 2, 3, or 4 your case statements will not be satisfied. You called input with the 's' option, meaning if you typed 1 at the input prompt the variable region will be the char array '1' which is not the same as the double array 1.
'1' == 1 % false
ans = logical
0
So change your case statements to check for the characters or change your input statement so it returns double values (1, 2) instead of char values ('1', '2').
region = '2';
switch region
case 1
disp('Region 1')
case '1'
disp('Region ''1''')
case 2
disp('Region 2')
case '2'
disp('Region ''2''')
end
Region '2'
  1 comentario
Kamryn Hall
Kamryn Hall el 27 de Nov. de 2021
Ah thank you. A while ago I changed the options to numbers instead of string, so I forgot to take out the 's' in the input statement. I appreciate you pointing that out!

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices 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!

Translated by