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

3 views (last 30 days)
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 !

Answers (1)

Steven Lord
Steven Lord on 26 Nov 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 Comment
Kamryn Hall
Kamryn Hall on 27 Nov 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!

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!