using scalars with short-circuiting or

36 views Asked by At

For a BMI calculator we need to create in programming class, I need to make sure that the values of size and weight are insinde of a certain range of numbers. Every time the program tells me that I can only compare scalars when using a short-circuiting or. However, after doing some reseaarch, I found floats to be scalars as well, so now I wonder what I did wrong.

Here you have the code I wrote by now:

weight = input("please enter your weight in kgs: ","s");
str2double(weight)
while isnan(weight)
weight = input("please enter your weight in kgs: ","s");
str2double(weight);
end
height = input("please enter your size in meters: ", "s");
str2double(height)

h = isscalar(size)
w = isscalar(height)

while isnan(height) || height > 2.2 || height < 1.3
hight = input("please enter your size in meters: ","s");
str2double(height);
end

I already tried to compare the two floats by themselves, but that did not work either. Then I did some research, which also does not help solving the problem. I now also changed the Name of the variable "size" to "height", but this does not help.

Here is one example input/output:

please enter your weight in kgs: 70

ans =

70

please enter your size in meters: 1.87

ans =

1.8700

h =

logical

0

w =

logical

0

Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY or ALL functions to reduce operands to logical scalar values.

1

There are 1 answers

0
Cris Luengo On

Here, height is a string, an array of characters (not scalar):

height = input("please enter your size in meters: ", "s");

Here, you convert the string to double, but you don’t store the result anywhere. height is still an array of characters:

str2double(height)

You might want to replace this last line with

height = str2double(height);

Or, better yet, remove the "s" from the input call. MATLAB will evaluate what the user types, and so will return a double in your case (but if the user types “[1,1]” or “'foo'”, it will return an array or a string, so you will have to test for that).