0% found this document useful (0 votes)
6 views85 pages

Unit-1 Part 2

part 2 ppt

Uploaded by

katrao39798
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views85 pages

Unit-1 Part 2

part 2 ppt

Uploaded by

katrao39798
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 85

Unit-II

BRANCHING, LOOPS & FUNCTION


HANDLING
MATLAB has four control Flow structures:
the if statement,
the for loop,
the while loop,and
the switch statement.
The ``if...end'' structure
MATLAB supports the variants of “if" construct.
◦ if ... end
◦ if ... else ... End
◦ if ... elseif ... else ... End
◦ Nested if

The simplest form of the if statement is


if expression
statements
end
some examples based on the familiar
quadratic formula.
1. discr = b*b - 4*a*c;
if discr < 0
disp('Warning: discriminant is
negative, roots are
imaginary’);
end
If else
If else
2. discr = b*b - 4*a*c;
if discr < 0
disp('Warning: discriminant is negative, roots are
imaginary’);
else
disp('Roots are real, but may be repeated’)
end
elseif
elseif
3. discr = b*b - 4*a*c;
if discr < 0
disp('Warning: discriminant is negative, roots are
imaginary’);
elseif discr == 0
disp('Discriminant is zero, roots are repeated’)
else
disp('Roots are real’)
end
Suppose the Random Bank now offers 9 percent interest on
balances of less than $5000, 12 percent for balances of $5000 or
more but less than $10 000, and 15 percent for balances of $10
000 or more. The following program calculates a customer’s new
balance after one year according to this scheme:

bal = 15000 * rand;


if bal < 5000
rate = 0.09;
elseif bal < 10000
rate = 0.12;
else
rate = 0.15;
end
newbal = bal + rate * bal;
format bank
disp( ’New balance is:’ )
disp( newbal )
v
Nested ifs
An if construct can contain further and
should not be confused with the elseif ladder. You have to be rather careful
with the elses. In general, else belongs to the most recent if which has not
been ended. The correct positioning of end is therefore very important, as the
next example demonstrates.ifs, and so on. This is called nesting
Suppose you want to compute the solution of a quadratic equation. You
may
want to check whether a = 0, to prevent a division by zero. Your program
could
contain the following nested ifs:
d = bˆ2 - 4*a*c;
if a ˜= 0
if d < 0
disp( ’Complex roots’ )
else
x1 = (-b + sqrt( d )) / (2*a);
x2 = (-b - sqrt( d )) / (2*a);
end % first end <<<<<<<<<<<<

end
The else belongs to the second if by default, as intended
d = bˆ2 - 4*a*c;
if a ˜= 0
if d < 0
disp( ’Complex roots’ )
end % first end moved up now <<<<<<<<<<<<
else
x1 = (-b + sqrt( d )) / (2*a);
x2 = (-b - sqrt( d )) / (2*a);

end

The end which has been moved now closes the second if. The result is that else belongs
to the first if instead of to the second one. Division by zero is therefore guaranteed,
instead of prevented!
1. elseif has no space between else and if (one word)

2. no semicolon (;) is needed at the end of lines containing if,


else, end

3. indentation of if block is not required but facilitate the


reading.

4. the end statement is required


Relational and logical operators
Multiple expressions can be handled in a single case statement
by enclosing
the case expression in a cell array

d = floor(10*rand);
switch d
case {2, 4, 6, 8}
disp( ’Even’ );
case {1, 3, 5, 7, 9}
disp( ’Odd’ );
otherwise
disp( ’Zero’ );
end
The switch statement executes certain statements based
on the value of a variable or expression. In this example it
is used to decide whether a random integer is 1, 2 or 3

d = floor(3*rand) + 1
switch d
case 1
disp( ’Thats a 1!’ );
case 2
disp( ’Thats a 2!’ );
otherwise
disp( ’Must be 3!’ );
end
LOOPS
FOR Loop
The for statement is used to repeat a group of statements a fixed number of times.
If the index of a for statement is used in the expression being repeated, the
expression can often be vectorized, saving a great deal of computing time.
Loop is another method to alter the flow of a computer program.
 In a loop, the execution of a command, or a group of commands, is repeated several
times consecutively.
Each round of execution is called a pass.
In each pass at least one variable, but usually more than one, or even all the variables
that are defined within the loop, are assigned new values.
MATLAB has two kinds of loops. In for-end loops the number of
passes is specified when the loop starts.
In while-end loops the number of passes is not known ahead of
time, and the looping process continues until a specified condition is
satisfied.
Both kinds of loops can be terminated at any time with the break
command
For - end Loops
for k=1:3:10
X = k^2
End

>> X =
1
X
16
X
49
X
100
for i = 1:5, disp(i), end
for i = 1:3, disp(i), end
for i = 1:0, disp(i), end
Can you see what’s happening?
The disp statement is repeated five times,three times, and not at all.
Square roots with Newton’s method
The square root x of any positive number a may be found using only the arithmetic
operations of addition, subtraction and division with Newton’s method. This is an
iterative (repetitive) procedure that refines an initial guess.
To introduce in a rather elementary way the notion of structured programming (to be
described in more detail in Chapter 3), let us consider the following plan.
The structure plan of the algorithm to find the square root and a program withsample
output for a=2 are as follows.
The structure plan:
◦ 1. Initialize a
◦ 2. Initialize x to a/2
◦ 3. Repeat 6 times (say)
◦ Replace x by (x + a/x)/2
◦ Display x
◦ 4. Stop.
The program:

a = 2;
x = a/2;
disp([’The approach to sqrt(a) for a = ’, num2str(a)])
for i = 1:6
x = (x + a / x) / 2;
disp( x )
end
disp( ’Matlab’’s value: ’ )
disp( sqrt(2) )
The output (after selecting format long) is as follows:
The approach to sqrt(a) for a = 2
1.50000000000000
1.41666666666667
1.41421568627451
1.41421356237469
1.41421356237310
1.41421356237310

Matlab’s value:
1.41421356237310
Factorials!
Run the following program to generate a list of n and n! (spoken as ‘n factorial’, or ‘n shriek’) where n! = 1 × 2 × 3 × . . . × (n − 1) × n.

n = 10;
fact = 1;
for k = 1:n
fact = k * fact;
disp( [k fact] )
end
Limit of a sequence
Consider the sequence
xn = an/n!, n = 1, 2, 3, . . .
where a is any constant, and n! is the factorial function defined
above.
The question is:
◦ What is the limit of this sequence as n gets indefinitely large?
◦ Let’s take the case a=10.
◦ If we try to compute xn directly we could get into trouble,
because n! gets large very rapidly as n increases, and numerical
overflow could occur.
However, the situation is neatly transformed if we spot that
x is related to x as follows:
n n−1 x
n

= ax /n.
n−1

There are no numerical problems now. (This relationship


between x and x is a typical kind of discovery by clever
n n−1

mathematicians.

The following program computes xn for a=10, and


increasing values of n.
a = 10;
x = 1;
k = 20; % number of terms
for n = 1:k
x = a * x / n;
The basic for construct
In general the most common form of the for loop (for use in a program, not on the
command line) is

for index = j:k


statements
end
or
for index = j:m:k
statements
end
Note the following points carefully:
1. j:k is a vector with elements j, j + 1, j + 2, . . . , k.
2. j:m:k is a vector with elements j, j +m, j +2m, . . . , such that the last
element does not exceed k if m>0, or is not less than k if m<0.
3. index must be a variable. Each time through the loop it will contain
the
next element of the vector j:k or j:m:k, and for each of these values
statements (which may be one or more statement) are carried out.
If the for construct has the form
for k = first:increment:last
Sample Problem: Sum of a series
Enter the number of terms 4
The sum of the series is: -0.125000
Enter the number of terms 20
The sum of the series is: -0.222216
(b) A user-defined function file that calculates sin(x) by adding n
terms of a
Taylor series is shown below.

>> Tsin(150,3)
ans =
0.6523
Tsin(150,7)
ans =
0.5000
Sample Problem: Modify vector elements
A vector is given by V= [5, 17, -3, 8, 0, -7, 12, 15, 20, -6, 6, 4, -7, 16]. Write a program as a script
file that doubles the elements that are positive and are divisible by 3 or 5, and, raises to the
power of 3 the elements that are negative but greater than -5.
The problem is solved by using a for-end loop that has an if - elseif – end conditional
statement inside.
Mistake ?
Multiple for loops can be nested,
n = 5; A = eye(n);
for j=2:n
◦ for i=1:j-1
◦ A(i,j)=i/j;
◦ A(j,i)=i/j;
◦ end
end
HW
Build in functions
Elementary math functions

You might also like