MATLAB Answers

# switch case & operators

43 views (last 30 days)
Sela Uguy on 22 Feb 2021
Edited: Jan on 22 Feb 2021
if (pop==1)
w=str2double(get(handles.edit_kg,'string'));
h=str2double(get(handles.edit_cm,'string'));
body=1e4*(w)/(h^2);
set(handles.textbmi,'string',sprintf('%.2f',body));
switch (body)
case (body < 17)
s = 'Underweight';
case (body >=17) && (body < 23)
s = 'Normal';
case (body >= 23) && (body < 27)
s = 'Overweight';
otherwise
s = 'Obese';
end
set(handles.textstatus,'string',s);
handles.textstatus = s;
end
##### 2 CommentsShowHide 1 older comment
dpb on 22 Feb 2021
One would then conclude that the value of body is not numeric and under 27
>> body=1; switch (body)
case (body < 17)
s = 'Underweight';
case (body >=17) && (body < 23)
s = 'Normal';
case (body >= 23) && (body < 27)
s = 'Overweight';
otherwise
s = 'Obese';
end
>> s
s =
'Underweight'
>> body=nan;
>> switch (body)
case (body < 17)
s = 'Underweight';
case (body >=17) && (body < 23)
s = 'Normal';
case (body >= 23) && (body < 27)
s = 'Overweight';
otherwise
s = 'Obese';
end
>> s
s =
'Obese'
>>
shows the SWITCH block works; ergo the value going in must not be what you think.
Set a breakpoint at the line computing body to see what's going on and find logic errors...

Sign in to comment.

### Answers (1)

Jan on 22 Feb 2021
Edited: Jan on 22 Feb 2021
This is not the purpose of SWITCH/CASE. Please read the documentationm again:
doc switch
SWITCH evaluates its argument, ibn your case the variable body. Then it compares it with the expressions after the case statements. If body is e.g. 18, you get:
switch 18
case FALSE % This is the value of (body < 17)
...
case TRUE % Value of (body >=17) && (body < 23)
...
But 18 is neither TRUE nor FALSE.
You want an IF command instead of SWITCH.
if (body < 17)
s = 'Underweight';
elseif (body >=17) && (body < 23)
s = 'Normal';
elseif (body >= 23) && (body < 27)
s = 'Overweight';
else
s = 'Obese';
end
You can simplify this: After body<17 has been excluded already, there is no need to check for body >= 17 again. So htis is sufficient:
if (body < 17)
s = 'Underweight';
elseif (body < 23)
s = 'Normal';
elseif (body < 27)
s = 'Overweight';
else
s = 'Obese';
end
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!