SlideShare a Scribd company logo
6
Most read
12
Most read
16
Most read
NUMERICAL METHODS WITH
MATLAB PROGRAMMING
By
A.DHARANI
ASSISTANT PROFFESSOR
PG DEPARTMENT OF MATHEMATICS
SRI SARADA NIKETAN COLLEGE FOR WOMEN
STATEMENT LEVEL CONTROL
STRUCTURES
 One way to think of computer programs is to consider how the
statements that compose the program are organized. Usually,
sections of computer code can be categorized into on of three
structures: sequences, selection structures and repetition
structures.
 Sequences: Sequences are lists of commands that are executed one
after another.
 Selection structure: A selection structure allows the programmer
to execute one command or group of commands if some criteria is
true and a second set of commands if the criteria is false. A selection
statement provides the means of choosing between these paths based
on a logical condition. The conditions that are evaluated often
contain relational and logical operators o r functions.
 Repetition structure: A repetition structure or loop, causes a
group of statements to be executed zero, one, or more times. The
number of times a loop is executed depends on either a counter or
the evaluation of a logical condition.
RELATIONAL OPERATORS
Relational Operators Interpretation
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
EXAMPLES
 MATLAB has six relational operators for comparing two
matrices of equal size, comparisons are either true or false
and most computer programs use the number 1 for true and
0 for false.
 x = [ 1 2 3 4 5 ];
 y = [-2 0 2 4 6];
 x<y
 returns
 ans=
 0 0 0 0 1
 which tells that the comparisons was false for the
first four elements but true for the last one.
MATLAB ALSO ALLOWS US TO COMPARE
COMPARISONS WITH LOGICAL OPERATORS:
AND, NOT, AND OR
Logical Operators interpretation
& and
~ not
| or
EXAMPLE FOR LOGICAL
OPERATORS
consider the following:
x = [ 1 2 3 4 5];
y = [ -2 0 2 4 6];
z = [ 8 8 8 8 8 ];
z>x & z>y
returns
ans=
1 1 1 1 1
Both z is greater than both x and y for every
element.
• Selection structures MATLAB offers two kinds of
selection structures: find and a family of if structures
• Find
The find command is unique to MATLAB, and can
often be used instead of both if and loop structures. The
usefulness of the find command is best described with
examples.
Assume that you have a list of temperatures
measured in a manufacturing process. If the
temperature is less than 95 degree F, them widgets
produced will be faulty:
temp = [ 100 98 94 101 93 ]
use the find function to determine which widgets are
family:
find(temp<95)
Returns a vector of element numbers;
ans=
3 5
Location of all elements greater than 9:
x = [ 1,2,3 10,5,1 3,12,2 8,3,1]
element = find(x>9)
[row, column] = find(x>9)
Returns
x =
1 2 3
10 5 1
3 12 2
8 3 1
Element =
2
7
row =
2
3
column =
1
2
The numbers 10 and 12 are the only two values greater than
9
IF , ELSE IF, ELSE:
EXAMPLE:
a = input (‘ enter a = ‘);
if a>0
disp (‘ a is positive’)
elseif a<0
disp (‘ a is negative’)
else
disp (‘ a is zero’)
end
Returns,
‘enter a = 5’
ans =
5 is positive
‘ enter a = -1’
ans =
-1 is negative
‘ enter a = 0’
ans =
zero
IF:
If the logical expression is true, the statement between if
and end are executed. If the logical expression is false, program
control jumps immediately to the statement following the end
statement.
ELSE IF:
It is a conditional statement performed after an if statement
that, if true, performs a function.
The elseif statement is only executed if the preceding if
expression evaluated to false, and the current elseif expression
evaluated to true.
ELSE:
Use else to specify a block of code to be executed, if the same
condition is false. Else doesn’t need a condition as it is the
default for everything where as else if is still an if so it needs a
condition.
. • Loops
A loop is a structure that allows you to repeat a set of statements.
In general, you should avoid loops in MATLAB because they are
seldom needed, and they can significantly increase the execution
time of a program.
For loops
In general, it Is possible to use either a for or a while loop in any
situation that requires a repetition structures. However, for loops
are the easier choice when you know how many times you want to
repeat a set of instructions.
The general format is
for index = expression
statements
end
Usually, the expression is a vector, and the statements are repeated
as many times as there are columns in the expression matrix. For
example, to find 5 raised to the 100th
power, first initialize a
running total:
total = 1;
for k = 1:100
total = total*5;
end
The first time through the loop, total = 1, so total ×5=5, the next line
through the loop, the value of total is updated to 5×5 equals 25,after 100
times through the loop, the final value is found, and corresponds to 5ˆ100.
Notice that the value of totalwas suppressed, so it won’t print out each
time through the loop. To recall the find value of total, type
total
which returns
total =
7.8886e+069
Another example of loop is,
for k = 1:4
k
end
returns
k =
1
k =
2
k=
3
k =
4
THE RULES FOR WRITING AND USING A FOR LOOP
ARE THE FOLLOWING:
• The index of a for loop must be a variable. Although k is often used
as the symbol for the index, any variable name can be used. The use
of k is strictly a style issue.
•If the expression matrix is the empty matrix, the loop will not be
executed. Control will pass to the statement following the end
statement.
• If the expression matrix is a scalar, the loop will be executed one
time, with the index containing the value of the scalar.
• If the expression is a row vector, each time through the loop the
index will contain the next column in the matrix.
• If the expression matrix, each time through the loop the index will
contain the next column in the matrix. This means that the index
will be a column vector.
• Upon completion of a for loop, the index contains the last value
used.
The colon operator can be used to define the expression matrix using
the following format:
for k = initial : increment : limit
• While loops:
The while loop is a structure used for repeating a set of
statements as long as specified condition is true. The general
format for this control structure is
while expression
Statements
end
The statements in the while loop are executed as long as the
real part of the expression has all nonzero elements. The
expression is usually a comparison using relational and logical
operators.
When the result of a comparison is true, the result is 1, and
therefore ‘nonzero’. The loop will continue repeating as long as
the comparison is still true. When the expression is evaluated
as false, control skips to the statement following the end
statement .
Consider the following example:
First initialize a:
a = 0;
Then find the smallest multiple of 3 that is less than 100:
while( a < 100 )
a = a+3;
end;
The last time through the loop a will start out as 99, then
will become 102 when 3 is added to 99. The smallest
multiple then becomes
a – 3
Which returns
ans =
99
The variable modified in the statements inside the loop
should include the variables in the expression, or else the
value of the expression will never change.
If the expression is always true, then the loop will execute
an infinite number of times.
COMMANDS AND FUNCTIONS
COMMAND MEANINGS
clock Determines the current time on the CPU clock
disp Displays matrix or test
else Defines the path if the result of an if statement is
false
elseif Defines the path if the result of an if statement is
false, and specifies a new logical test
end Identifies the end of a control structure
etime Finds elapsed time
find Determines which elements in a matrix meet the
input criteria
for Generates a loop structure
fprintf Prints formatted information
function Identifies an M-files as a function
if Tests a logical expression
COMMAND MEANING
input Prompts the user to enter a value
meshgrid Maps two input vectors onto two 2-D
matrices
nargin Determines the number of input
arguments in a function
nargout Determines the number of output
arguments from a function
num2string Converts an array into a string
ones Creates a matrix of ones
tic Starts a timing sequence
toc Stops a timing sequence
while Generates a loop structure
zeros Creates a matrix of zeros
THANK
YOU
Ad

Recommended

Chapter 3 - Programming in Matlab. aaaapptx
Chapter 3 - Programming in Matlab. aaaapptx
danartalabani
 
7_Programming in MATLAB For Enginee.pptx
7_Programming in MATLAB For Enginee.pptx
SungaleliYuen
 
04 a ch03_programacion
04 a ch03_programacion
universidad del valle colombia
 
Matlab tutorial 3
Matlab tutorial 3
Norhan Abdalla
 
3.pdf
3.pdf
DEVENDRA PRATAP SINGH
 
ET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDI
ET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDI
IrlanMalik
 
Matlab for diploma students(1)
Matlab for diploma students(1)
Retheesh Raj
 
Csci101 lect02 selection_andlooping
Csci101 lect02 selection_andlooping
Elsayed Hemayed
 
Matlab_basic2013_1.pdf
Matlab_basic2013_1.pdf
abdul basit
 
Mbd dd
Mbd dd
Aditya Choudhury
 
Matlab Workshop Presentation
Matlab Workshop Presentation
Jairo Maldonado-Contreras
 
BEN520 FUNDAMENTALS OF BOENGINEERING II-4 week-lecture 4.pptx
BEN520 FUNDAMENTALS OF BOENGINEERING II-4 week-lecture 4.pptx
chemeng87
 
L06
L06
Saurav Rahman
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
amanabr
 
Loops presentationnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Loops presentationnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
divyapriya balasubramani
 
Programming.pptVBVBBMCGHFGFDFDHGDFKJKJKKJ;J
Programming.pptVBVBBMCGHFGFDFDHGDFKJKJKKJ;J
AlthimeseAnderson
 
Introduction to matlab
Introduction to matlab
vikrammutneja1
 
5. Summing Series.pptx
5. Summing Series.pptx
HassanShah396906
 
Programming with matlab session 5 looping
Programming with matlab session 5 looping
Infinity Tech Solutions
 
Seminar on MATLAB
Seminar on MATLAB
Dharmesh Tank
 
Matlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processing
Dr. Manjunatha. P
 
Matlab ch1 (1)
Matlab ch1 (1)
mohsinggg
 
Matlab operators
Matlab operators
Aswin Pv
 
Intro to matlab
Intro to matlab
Norhan Mohamed
 
The Basics of MATLAB
The Basics of MATLAB
Muhammad Alli
 
Programming for Problem Solving
Programming for Problem Solving
Kathirvel Ayyaswamy
 
Matlab Basic Tutorial
Matlab Basic Tutorial
Muhammad Rizwan
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
Q1_TLE 8_Week 1- Day 1 tools and equipment
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
 

More Related Content

Similar to NUMERICAL METHODS WITH MATLAB PROGRAMMING (20)

Matlab_basic2013_1.pdf
Matlab_basic2013_1.pdf
abdul basit
 
Mbd dd
Mbd dd
Aditya Choudhury
 
Matlab Workshop Presentation
Matlab Workshop Presentation
Jairo Maldonado-Contreras
 
BEN520 FUNDAMENTALS OF BOENGINEERING II-4 week-lecture 4.pptx
BEN520 FUNDAMENTALS OF BOENGINEERING II-4 week-lecture 4.pptx
chemeng87
 
L06
L06
Saurav Rahman
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
amanabr
 
Loops presentationnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Loops presentationnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
divyapriya balasubramani
 
Programming.pptVBVBBMCGHFGFDFDHGDFKJKJKKJ;J
Programming.pptVBVBBMCGHFGFDFDHGDFKJKJKKJ;J
AlthimeseAnderson
 
Introduction to matlab
Introduction to matlab
vikrammutneja1
 
5. Summing Series.pptx
5. Summing Series.pptx
HassanShah396906
 
Programming with matlab session 5 looping
Programming with matlab session 5 looping
Infinity Tech Solutions
 
Seminar on MATLAB
Seminar on MATLAB
Dharmesh Tank
 
Matlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processing
Dr. Manjunatha. P
 
Matlab ch1 (1)
Matlab ch1 (1)
mohsinggg
 
Matlab operators
Matlab operators
Aswin Pv
 
Intro to matlab
Intro to matlab
Norhan Mohamed
 
The Basics of MATLAB
The Basics of MATLAB
Muhammad Alli
 
Programming for Problem Solving
Programming for Problem Solving
Kathirvel Ayyaswamy
 
Matlab Basic Tutorial
Matlab Basic Tutorial
Muhammad Rizwan
 
Matlab_basic2013_1.pdf
Matlab_basic2013_1.pdf
abdul basit
 
BEN520 FUNDAMENTALS OF BOENGINEERING II-4 week-lecture 4.pptx
BEN520 FUNDAMENTALS OF BOENGINEERING II-4 week-lecture 4.pptx
chemeng87
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
amanabr
 
Loops presentationnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Loops presentationnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
divyapriya balasubramani
 
Programming.pptVBVBBMCGHFGFDFDHGDFKJKJKKJ;J
Programming.pptVBVBBMCGHFGFDFDHGDFKJKJKKJ;J
AlthimeseAnderson
 
Introduction to matlab
Introduction to matlab
vikrammutneja1
 
Programming with matlab session 5 looping
Programming with matlab session 5 looping
Infinity Tech Solutions
 
Matlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processing
Dr. Manjunatha. P
 
Matlab ch1 (1)
Matlab ch1 (1)
mohsinggg
 
Matlab operators
Matlab operators
Aswin Pv
 
The Basics of MATLAB
The Basics of MATLAB
Muhammad Alli
 

Recently uploaded (20)

List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
Q1_TLE 8_Week 1- Day 1 tools and equipment
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Rajdeep Bavaliya
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
AndrewBorisenko3
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
Vitamin and Nutritional Deficiencies.pptx
Vitamin and Nutritional Deficiencies.pptx
Vishal Chanalia
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
Q1_TLE 8_Week 1- Day 1 tools and equipment
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Rajdeep Bavaliya
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
AndrewBorisenko3
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
Vitamin and Nutritional Deficiencies.pptx
Vitamin and Nutritional Deficiencies.pptx
Vishal Chanalia
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
Ad

NUMERICAL METHODS WITH MATLAB PROGRAMMING

  • 1. NUMERICAL METHODS WITH MATLAB PROGRAMMING By A.DHARANI ASSISTANT PROFFESSOR PG DEPARTMENT OF MATHEMATICS SRI SARADA NIKETAN COLLEGE FOR WOMEN
  • 2. STATEMENT LEVEL CONTROL STRUCTURES  One way to think of computer programs is to consider how the statements that compose the program are organized. Usually, sections of computer code can be categorized into on of three structures: sequences, selection structures and repetition structures.  Sequences: Sequences are lists of commands that are executed one after another.  Selection structure: A selection structure allows the programmer to execute one command or group of commands if some criteria is true and a second set of commands if the criteria is false. A selection statement provides the means of choosing between these paths based on a logical condition. The conditions that are evaluated often contain relational and logical operators o r functions.  Repetition structure: A repetition structure or loop, causes a group of statements to be executed zero, one, or more times. The number of times a loop is executed depends on either a counter or the evaluation of a logical condition.
  • 3. RELATIONAL OPERATORS Relational Operators Interpretation < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to ~= Not equal to
  • 4. EXAMPLES  MATLAB has six relational operators for comparing two matrices of equal size, comparisons are either true or false and most computer programs use the number 1 for true and 0 for false.  x = [ 1 2 3 4 5 ];  y = [-2 0 2 4 6];  x<y  returns  ans=  0 0 0 0 1  which tells that the comparisons was false for the first four elements but true for the last one.
  • 5. MATLAB ALSO ALLOWS US TO COMPARE COMPARISONS WITH LOGICAL OPERATORS: AND, NOT, AND OR Logical Operators interpretation & and ~ not | or
  • 6. EXAMPLE FOR LOGICAL OPERATORS consider the following: x = [ 1 2 3 4 5]; y = [ -2 0 2 4 6]; z = [ 8 8 8 8 8 ]; z>x & z>y returns ans= 1 1 1 1 1 Both z is greater than both x and y for every element.
  • 7. • Selection structures MATLAB offers two kinds of selection structures: find and a family of if structures • Find The find command is unique to MATLAB, and can often be used instead of both if and loop structures. The usefulness of the find command is best described with examples. Assume that you have a list of temperatures measured in a manufacturing process. If the temperature is less than 95 degree F, them widgets produced will be faulty: temp = [ 100 98 94 101 93 ] use the find function to determine which widgets are family: find(temp<95) Returns a vector of element numbers; ans= 3 5
  • 8. Location of all elements greater than 9: x = [ 1,2,3 10,5,1 3,12,2 8,3,1] element = find(x>9) [row, column] = find(x>9) Returns x = 1 2 3 10 5 1 3 12 2 8 3 1 Element = 2 7 row = 2 3 column = 1 2 The numbers 10 and 12 are the only two values greater than 9
  • 9. IF , ELSE IF, ELSE: EXAMPLE: a = input (‘ enter a = ‘); if a>0 disp (‘ a is positive’) elseif a<0 disp (‘ a is negative’) else disp (‘ a is zero’) end Returns, ‘enter a = 5’ ans = 5 is positive ‘ enter a = -1’ ans = -1 is negative ‘ enter a = 0’ ans = zero
  • 10. IF: If the logical expression is true, the statement between if and end are executed. If the logical expression is false, program control jumps immediately to the statement following the end statement. ELSE IF: It is a conditional statement performed after an if statement that, if true, performs a function. The elseif statement is only executed if the preceding if expression evaluated to false, and the current elseif expression evaluated to true. ELSE: Use else to specify a block of code to be executed, if the same condition is false. Else doesn’t need a condition as it is the default for everything where as else if is still an if so it needs a condition.
  • 11. . • Loops A loop is a structure that allows you to repeat a set of statements. In general, you should avoid loops in MATLAB because they are seldom needed, and they can significantly increase the execution time of a program. For loops In general, it Is possible to use either a for or a while loop in any situation that requires a repetition structures. However, for loops are the easier choice when you know how many times you want to repeat a set of instructions. The general format is for index = expression statements end Usually, the expression is a vector, and the statements are repeated as many times as there are columns in the expression matrix. For example, to find 5 raised to the 100th power, first initialize a running total: total = 1; for k = 1:100 total = total*5; end
  • 12. The first time through the loop, total = 1, so total ×5=5, the next line through the loop, the value of total is updated to 5×5 equals 25,after 100 times through the loop, the final value is found, and corresponds to 5ˆ100. Notice that the value of totalwas suppressed, so it won’t print out each time through the loop. To recall the find value of total, type total which returns total = 7.8886e+069 Another example of loop is, for k = 1:4 k end returns k = 1 k = 2 k= 3 k = 4
  • 13. THE RULES FOR WRITING AND USING A FOR LOOP ARE THE FOLLOWING: • The index of a for loop must be a variable. Although k is often used as the symbol for the index, any variable name can be used. The use of k is strictly a style issue. •If the expression matrix is the empty matrix, the loop will not be executed. Control will pass to the statement following the end statement. • If the expression matrix is a scalar, the loop will be executed one time, with the index containing the value of the scalar. • If the expression is a row vector, each time through the loop the index will contain the next column in the matrix. • If the expression matrix, each time through the loop the index will contain the next column in the matrix. This means that the index will be a column vector. • Upon completion of a for loop, the index contains the last value used. The colon operator can be used to define the expression matrix using the following format: for k = initial : increment : limit
  • 14. • While loops: The while loop is a structure used for repeating a set of statements as long as specified condition is true. The general format for this control structure is while expression Statements end The statements in the while loop are executed as long as the real part of the expression has all nonzero elements. The expression is usually a comparison using relational and logical operators. When the result of a comparison is true, the result is 1, and therefore ‘nonzero’. The loop will continue repeating as long as the comparison is still true. When the expression is evaluated as false, control skips to the statement following the end statement . Consider the following example: First initialize a: a = 0; Then find the smallest multiple of 3 that is less than 100:
  • 15. while( a < 100 ) a = a+3; end; The last time through the loop a will start out as 99, then will become 102 when 3 is added to 99. The smallest multiple then becomes a – 3 Which returns ans = 99 The variable modified in the statements inside the loop should include the variables in the expression, or else the value of the expression will never change. If the expression is always true, then the loop will execute an infinite number of times.
  • 16. COMMANDS AND FUNCTIONS COMMAND MEANINGS clock Determines the current time on the CPU clock disp Displays matrix or test else Defines the path if the result of an if statement is false elseif Defines the path if the result of an if statement is false, and specifies a new logical test end Identifies the end of a control structure etime Finds elapsed time find Determines which elements in a matrix meet the input criteria for Generates a loop structure fprintf Prints formatted information function Identifies an M-files as a function if Tests a logical expression
  • 17. COMMAND MEANING input Prompts the user to enter a value meshgrid Maps two input vectors onto two 2-D matrices nargin Determines the number of input arguments in a function nargout Determines the number of output arguments from a function num2string Converts an array into a string ones Creates a matrix of ones tic Starts a timing sequence toc Stops a timing sequence while Generates a loop structure zeros Creates a matrix of zeros