5. Control Loops for, while if

if-else-end Constructions

The simplest form is

if expression

commands evaluated if expression is true

end

but could be of the more detailed form

if expression1

    commands evaluated if expression1 is true

elseif expression2

    commands evaluated if expression2 is true

elseif expression3

    commands evaluated if expression3 is true

.....................

else

    commands evaluated if no other expression is true

end

Example 1: Let us consider a very simple situation firstly. Suppose a shop offers a 5% discount on bills over $100. Execute the following M-file for both $78.85 and then $122.40.

clear all

bill=78.85;

if bill>100

    bill=bill*0.95;

end

format bank

final_charge=bill

Example 2: The following M-file calculates the current amount of income tax due on a given taxable income. It also introduces MATLAB’s input command which enables data to be input from the keyboard when required by printing out a suitable message. Execute the following M-file for a variety of different taxable incomes:

clear all % file available in M-files folder as file3.m

income=input(’enter taxable income:>>’)

format bank

if income <= 5400

    tax=0

elseif income <= 20700

    tax=(income-5400)*0.20

elseif income <= 38000

    tax=3060+(income-20700)*0.34

elseif income <= 50000

    tax=8942+(income-38000)*0.43

else

    tax=14102+(income-50000)*0.47

end

Example 3: Most if constructions occur inside a for or while loop. In how many ways can x = 59, 650 be written as the sum of squares of two integers m and n? In other words, find all integer pairs m, n such that m2 + n2 = x, which is equivalent to asking whether n = √x − m2 is an integer. Execute the following:

clear all

x=59650

for m=1:sqrt(x)                    % m cannot exceed sqrt(x) if m^2+n^2=x

     n=sqrt(x-m^2);              % next test if n is an integer

     if n = = round(n)            % no space between the two equal signs

            pair=[m,n]

     end

end