MATLAB: How to properly combine “and”, “or” and “if”

andifor

Hi,
My function needs to calculate the cost of a train ticket. The first mile is $2. Each additional mile up to 10 miles is 25 cents. Each additional mile over 10 miles is 10 cents. Children under or equal to 18 and seniors older or equal to 60 pay 80%. The inputs to the function are distance and age.
I have below code, but for some reason it doesn't take the discount into consideration.
function price=fare(d,a)
if 18<a<60 && d <=1
price=2
elseif 18<a<60 && 1<d<10
price=2+d*0.25
elseif 18<a<60 && d==10
price=2+9*0.25
elseif 18<a<60 && d>10
price=2+(9*0.25)+((d-10)*0.10)
elseif a<=18 || a>=60 && d <=1
price=2*0.80
elseif a<=18 || a>=60 && 1<d<10
price=(2+d*0.25)*0.80
elseif a<=18 || a>=60 && d==10
price=(2+9*0.25)*0.80
elseif a<=18 || a>=60 && d>10
price=(2+(9*0.25)+((d-10)*0.10))*0.80
end

Best Answer

Note that this code fragment ALWAYS returns true
18<a<60
since regardless of the value of a, (18<a) ALWAYS returns either 0 or 1, i.e., false or true. Are both 0 and 1 less than 60? Yes.
Just because you choose to use some nice mathematical short hand, does not mean that it is equivalent to
(18<a) && (a<60)
You use similar expressions repeatedly in your code. A bad idea.