SlideShare a Scribd company logo
1
Chapter 3
Programming in MATLAB
• A computer program is a sequence of computer commands.
• In a simple program the commands are executed one after the
other in the order they are typed.
• Script Files:
Input Command
Output Commands
• Relational and Logical operators
• Conditional statements
• The Switch-Case statement
• Loops (for and while)
Introduction
2
In MATLAB script files are created and edited in the
Editor/Debugger Window. This window is opened from the
Command Window. In the File menu, select New, and then
select Script or press the shortcut key ( Ctrl + N ).
3
3.1 Script Files
Creating and Saving a Script File & Running a Script File
Figure 1-6: Creatie
3.1.1 Input Command
The form of the input command is:
4
The string is actually a vector that contains the numeric codes for the characters.
The length of S is the number of characters. A quotation within the string is
indicated by two quotation marks.
5
3.1.2 Output Commands
CHATER
1- The disp command is used to display the elements of a variable without
displaying the name of the variable, and to display text. The format of the disp
command is:
2- The fprintf command is used to display text and data of variables on the screen
with the same line.
The format of the fprintf command is:
6
CHAPTER 5
3.2 Relational and Logical Operators
7
• A relational operator compares two numbers by determining whether a
comparison statement is true or false.
• Relational operators are used as arithmetic operators within a mathematical
expression. The result can be used in other mathematical operations.
• If two arrays are compared (only arrays of the same size can be compared),
the comparison is done element-by-element, and the result is a logical array
of the same size with 1s and 0s.
CHAPTER 5
3.2 Relational and Logical Operators
8
CHAPTER 3
3.2 Relational and Logical Operators
9
Logical operators
• Logical operators have numbers as operands. A nonzero number
is true, and a zero number is false.
CHAPTER 3
3.2 Relational and Logical Operators
10
Logical operators
11
Expression Evaluates As Because
A < B false A(1,1) is not less than B(1,1).
A < (B + 1) true Every element of A is less
than that same element
of B with 1 added.
A & B false A(1,2) & B(1,2) is false.
B < 5 true Every element of B is less
than 5.
Example
Given matrices A and B
A = [1 0 ; 2 3]
B = [1 1 ; 3 4]
Logical Operators
(Scalar logical)
Operator Name Description
&& AND A&&B
Returns True if both A and B evaluate to true
And False if they do not
conditional
|| OR A||B
Returns True if either A or B or both evaluate to
True And False if they do not
conditional
3.2 Relational and Logical Operators
13
Built-in logical functions
CHAPTER 5
3.2 Relational and Logical Operators
14
Built-in logical functions
3.3 Conditional Statements
15
• A conditional statement is a command that allows MATLAB to make a decision
of whether to execute a group of commands that follow the conditional
statement, or to skip these commands.
16
If statements
•Syntax:
•If logical expression
•Statements
•end
17
3.3.1 The if-end Structure
18
Example
Calculate the square root y of the variable x only when the
value of x is non-negative.
The command y = sqrt(x) is only executed if x >=0 is true.
The variable y is not defined when x >=0 is false.
>> if x >= 0
y = sqrt(x)
end
Example
A worker is paid according to his hourly wage up to 40 hours, and 50%
more for overtime. Write a program in a script file that calculates the pay
to a worker. The program asks the user to enter the number of hours and
the hourly wage. The program then displays the pay.
20
3.3.2 The if-else-end Structure
21
Example
Give MATLAB code to calculate y where y = -1 when x < 0 and
y = 2 when x > 2.
>> if x < 0
y = -1
elseif x > 2
y = 2
end
The statement y = -1 is executed only if the condition x<0 is
true.
The statement y = 2 is executed only if the condition x<0 is
false and the condition x>2 is true.
The variable y is not defined when both conditions are false,
that is, when 0 <= x <= 2.
22
3.3.3 The if-elseif-else-end Structure
23
Example
The value of f(x) is -2x when x < 0; x(x-2) when x is in [0, 2] and
log(x-1) otherwise. Calculate f(x).
>> if x < 0
f = -2*x
elseif x <= 2
f = x*(x-2)
else
f = log(x-1)
end
The first block is executed when x < 0 is true.
The elseif is only reached if x < 0 is false, that is x >= 0, so you
only need to check x <=2.
The else is reached when all previous conditions are false, that is x
> 2.
24
Exercise
Write a MATLAB if statement to calculate y where y = 1 if
x > pi/2, y = sin(x) if x is in [0, pi/2] and y = 0
otherwise.
Answer:
if x > pi/2
y = 1
elseif x >= 0
y = sin(x)
else
y = 0
end
25
3.4 The switch-case Statement
• The switch-case statement is another method that can be used to direct the
flow of a program.
• It provides a means for choosing one group of commands for execution out of
several possible groups.
• If there is more than one match, only the first
matching case is executed.
• If no match is found and the otherwise
statement is present, the group of
commands between otherwise and end is
executed; if otherwise not present, none of
the command groups is executed.
• A case statement can have more than one
value: {value1, value2, value3, ...}.
• Break statement not required as C++.
3.5 Loops
3.5.1 for-end Loops
27
P
A
S
S
k = 1:2:9
PASS 1: k=1
PASS 2: k=1+2=3
PASS 3: k=3+2=5
PASS 4: k=5+2=7
PASS 5: k=7+2=9
can be +ve or –ve
Default value is 1
for k=1:3:10
x = k^2
end
x=
1 16 49 100
EXAMPLE
LAST PASS:
If s is +ve (<=)
If s is –ve (>=)
Number of passes is known ahead of time
28
Example
Given an integer n, calculate the sum of the integers k2
for k =
1,...,n.
The variable s is initialised to 0.
The index variable k starts at 1, then increases in steps of 1 until it
reaches n.
Each time through the loop the value of k2
is added to s.
Sol:
s = 0;
n=input('Enter the number of terms');
for k = 1:n
s = s + k^2;
end
fprintf('The sum of the series is: %f','S')
29
CHAPTER 5
False
A variable should be assigned
the variable again must be assigned
a new value
x=1
while x<=15
x=2*x
end
EXAMPLE
x = 1
x = 2
x = 4
x = 8
x = 16
stop the execution of an indefinite
loop by pressing the Ctrl + C or Ctrl
+ Break keys.
Indefinite loop
Number of passes is NOT known in advance
3.5 Loops
3.5.2 while-end Loops
30
3.6 The Break and Continue Commands
Write a program in a script file
that finds the smallest odd
integer that is dividable by 11
and whose square root is
greater than 132. Use a loop in
the program. The loop should
start from 1 and stop when the
number is found. The program
prints the message “The
required number is:” and then
prints the number.
for x=1:inf
if rem(x,11)==0 & sqrt(x)>132
break
else continue
end
end
fprintf('n The required number is: %2.3f
n',x)
x=1;
while true
if rem(x,11)==0 & sqrt(x)>132
break
end
x=x+1;
end
fprintf('The required number is: %0.2f
n',x)
31
CHAPTER
FOUR
EXAMPLE 1
Use a for-end loop in a script file to calculate the
sum of the first n terms of the series:
Execute the script file for n = 4 and n = 20.
TIPS:
1. k=1 and n=4 & n=20
2. Use input command to
enter n separately.
3. Define S=0;
4. Write for-end loop and
enter the math expression
in between.
5. (-1)^k*k/2^k
6. Use an output command
to display the result
S=0;
n=input(‘Enter the number of terms’);
for k=1:n;
S=S+(-1)^k*k/2^k;
end
fprintf(‘The sum of the series is: %f',S)
32
EXAMPLE 2
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 dividable by 3 or 5, and, raises
to the power of 3 the elements that are
negative but greater than –5.
TIPS:
1. Define vector V
2. Use for-end loop command, k=1,
n=length(V)
3. If V elements are +ve & divisible by 3 or
5: make them double
4. If V elements are –ve & greater than -5:
^3
5. disp(V)

More Related Content

PPTX
NUMERICAL METHODS WITH MATLAB PROGRAMMING
PDF
04 a ch03_programacion
PPTX
7_Programming in MATLAB For Enginee.pptx
PDF
Matlab tutorial 3
PPTX
Loops presentationnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
PDF
Dsp lab _eec-652__vi_sem_18012013
PDF
Dsp lab _eec-652__vi_sem_18012013
PPT
ET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDI
NUMERICAL METHODS WITH MATLAB PROGRAMMING
04 a ch03_programacion
7_Programming in MATLAB For Enginee.pptx
Matlab tutorial 3
Loops presentationnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
ET DAH SI HAN HAN ADIKNYA SI WIDIANTORO RIBUT MULU SAMA ABANG WIDI

Similar to Chapter 3 - Programming in Matlab. aaaapptx (20)

PDF
Matlab_basic2013_1.pdf
PPTX
Csci101 lect02 selection_andlooping
PPTX
Chap2programing.pptxdxnDSnfkezjnfqjdsckjqds
PPTX
5. Summing Series.pptx
PPTX
Matlab for diploma students(1)
PPTX
PDF
Slide 6_Control Structures.pdf
PPTX
Conditional Control in MATLAB Scripts
PPTX
“Python” or “CPython” is written in C/C+
PPT
Python Control structures
PDF
learn basic to advance C Programming Notes
PPTX
Programming Fundamentals in Python - Selection Structure
PPTX
Programming note C#
PPTX
Matlab Workshop Presentation
PPTX
Matlab ch1 (1)
PDF
23CSC101T PSPP python programming - UNIT 3.pdf
PDF
23CSC101T PSPP python program - UNIT 3.pdf
PDF
Programming for Problem Solving
PPTX
Introduction to matlab
Matlab_basic2013_1.pdf
Csci101 lect02 selection_andlooping
Chap2programing.pptxdxnDSnfkezjnfqjdsckjqds
5. Summing Series.pptx
Matlab for diploma students(1)
Slide 6_Control Structures.pdf
Conditional Control in MATLAB Scripts
“Python” or “CPython” is written in C/C+
Python Control structures
learn basic to advance C Programming Notes
Programming Fundamentals in Python - Selection Structure
Programming note C#
Matlab Workshop Presentation
Matlab ch1 (1)
23CSC101T PSPP python programming - UNIT 3.pdf
23CSC101T PSPP python program - UNIT 3.pdf
Programming for Problem Solving
Introduction to matlab
Ad

More from danartalabani (13)

PPTX
Chapter 4 Two Dimensional Plots aaa---.pptx
PPTX
Chapter 2 Arrays part B aaaaaaaaaaa.pptx
PPTX
Chapter 1 Starting With MATLAB matlab.pptx
PPTX
reinforcing stee reinforcing stee zhi99.pptx
PPTX
reinforcing steel reinforcing steereinforcing stee.pptx
PPTX
Presentation basic Presentation basic (2).pptx
PPTX
CIVIL2 Civil Civil Civil Civil Civil.pptx
PPTX
Civil Civil Civil Civil Civil Civil.pptx
PPTX
basic civil basic basic basic basic.pptx
PPT
Vectors Vectors Vectors Vectors Vectors1.ppt
PPT
MULTIPLE INTEGRALS MULTIPLE INTEGRALS upload.ppt
PPT
FUNCTIONS LIMITS AND CONTINUITYLIMITS AND CONTINUITY.ppt
PPT
LIMITS AND CONTINUITY LIMITS AND CONTINUITY.ppt
Chapter 4 Two Dimensional Plots aaa---.pptx
Chapter 2 Arrays part B aaaaaaaaaaa.pptx
Chapter 1 Starting With MATLAB matlab.pptx
reinforcing stee reinforcing stee zhi99.pptx
reinforcing steel reinforcing steereinforcing stee.pptx
Presentation basic Presentation basic (2).pptx
CIVIL2 Civil Civil Civil Civil Civil.pptx
Civil Civil Civil Civil Civil Civil.pptx
basic civil basic basic basic basic.pptx
Vectors Vectors Vectors Vectors Vectors1.ppt
MULTIPLE INTEGRALS MULTIPLE INTEGRALS upload.ppt
FUNCTIONS LIMITS AND CONTINUITYLIMITS AND CONTINUITY.ppt
LIMITS AND CONTINUITY LIMITS AND CONTINUITY.ppt
Ad

Recently uploaded (20)

PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
01-Introduction-to-Information-Management.pdf
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
Presentation on HIE in infants and its manifestations
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Cell Structure & Organelles in detailed.
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Institutional Correction lecture only . . .
PDF
Classroom Observation Tools for Teachers
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
Computing-Curriculum for Schools in Ghana
Supply Chain Operations Speaking Notes -ICLT Program
01-Introduction-to-Information-Management.pdf
A systematic review of self-coping strategies used by university students to ...
Presentation on HIE in infants and its manifestations
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Cell Structure & Organelles in detailed.
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Microbial disease of the cardiovascular and lymphatic systems
O7-L3 Supply Chain Operations - ICLT Program
102 student loan defaulters named and shamed – Is someone you know on the list?
VCE English Exam - Section C Student Revision Booklet
O5-L3 Freight Transport Ops (International) V1.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Institutional Correction lecture only . . .
Classroom Observation Tools for Teachers
GDM (1) (1).pptx small presentation for students
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Computing-Curriculum for Schools in Ghana

Chapter 3 - Programming in Matlab. aaaapptx

  • 2. • A computer program is a sequence of computer commands. • In a simple program the commands are executed one after the other in the order they are typed. • Script Files: Input Command Output Commands • Relational and Logical operators • Conditional statements • The Switch-Case statement • Loops (for and while) Introduction 2
  • 3. In MATLAB script files are created and edited in the Editor/Debugger Window. This window is opened from the Command Window. In the File menu, select New, and then select Script or press the shortcut key ( Ctrl + N ). 3 3.1 Script Files Creating and Saving a Script File & Running a Script File Figure 1-6: Creatie
  • 4. 3.1.1 Input Command The form of the input command is: 4 The string is actually a vector that contains the numeric codes for the characters. The length of S is the number of characters. A quotation within the string is indicated by two quotation marks.
  • 5. 5 3.1.2 Output Commands CHATER 1- The disp command is used to display the elements of a variable without displaying the name of the variable, and to display text. The format of the disp command is: 2- The fprintf command is used to display text and data of variables on the screen with the same line. The format of the fprintf command is:
  • 6. 6
  • 7. CHAPTER 5 3.2 Relational and Logical Operators 7 • A relational operator compares two numbers by determining whether a comparison statement is true or false. • Relational operators are used as arithmetic operators within a mathematical expression. The result can be used in other mathematical operations. • If two arrays are compared (only arrays of the same size can be compared), the comparison is done element-by-element, and the result is a logical array of the same size with 1s and 0s.
  • 8. CHAPTER 5 3.2 Relational and Logical Operators 8
  • 9. CHAPTER 3 3.2 Relational and Logical Operators 9 Logical operators • Logical operators have numbers as operands. A nonzero number is true, and a zero number is false.
  • 10. CHAPTER 3 3.2 Relational and Logical Operators 10 Logical operators
  • 11. 11 Expression Evaluates As Because A < B false A(1,1) is not less than B(1,1). A < (B + 1) true Every element of A is less than that same element of B with 1 added. A & B false A(1,2) & B(1,2) is false. B < 5 true Every element of B is less than 5. Example Given matrices A and B A = [1 0 ; 2 3] B = [1 1 ; 3 4]
  • 12. Logical Operators (Scalar logical) Operator Name Description && AND A&&B Returns True if both A and B evaluate to true And False if they do not conditional || OR A||B Returns True if either A or B or both evaluate to True And False if they do not conditional
  • 13. 3.2 Relational and Logical Operators 13 Built-in logical functions
  • 14. CHAPTER 5 3.2 Relational and Logical Operators 14 Built-in logical functions
  • 15. 3.3 Conditional Statements 15 • A conditional statement is a command that allows MATLAB to make a decision of whether to execute a group of commands that follow the conditional statement, or to skip these commands.
  • 16. 16 If statements •Syntax: •If logical expression •Statements •end
  • 17. 17 3.3.1 The if-end Structure
  • 18. 18 Example Calculate the square root y of the variable x only when the value of x is non-negative. The command y = sqrt(x) is only executed if x >=0 is true. The variable y is not defined when x >=0 is false. >> if x >= 0 y = sqrt(x) end
  • 19. Example A worker is paid according to his hourly wage up to 40 hours, and 50% more for overtime. Write a program in a script file that calculates the pay to a worker. The program asks the user to enter the number of hours and the hourly wage. The program then displays the pay.
  • 21. 21 Example Give MATLAB code to calculate y where y = -1 when x < 0 and y = 2 when x > 2. >> if x < 0 y = -1 elseif x > 2 y = 2 end The statement y = -1 is executed only if the condition x<0 is true. The statement y = 2 is executed only if the condition x<0 is false and the condition x>2 is true. The variable y is not defined when both conditions are false, that is, when 0 <= x <= 2.
  • 23. 23 Example The value of f(x) is -2x when x < 0; x(x-2) when x is in [0, 2] and log(x-1) otherwise. Calculate f(x). >> if x < 0 f = -2*x elseif x <= 2 f = x*(x-2) else f = log(x-1) end The first block is executed when x < 0 is true. The elseif is only reached if x < 0 is false, that is x >= 0, so you only need to check x <=2. The else is reached when all previous conditions are false, that is x > 2.
  • 24. 24 Exercise Write a MATLAB if statement to calculate y where y = 1 if x > pi/2, y = sin(x) if x is in [0, pi/2] and y = 0 otherwise. Answer: if x > pi/2 y = 1 elseif x >= 0 y = sin(x) else y = 0 end
  • 25. 25 3.4 The switch-case Statement • The switch-case statement is another method that can be used to direct the flow of a program. • It provides a means for choosing one group of commands for execution out of several possible groups. • If there is more than one match, only the first matching case is executed. • If no match is found and the otherwise statement is present, the group of commands between otherwise and end is executed; if otherwise not present, none of the command groups is executed. • A case statement can have more than one value: {value1, value2, value3, ...}. • Break statement not required as C++.
  • 26. 3.5 Loops 3.5.1 for-end Loops 27 P A S S k = 1:2:9 PASS 1: k=1 PASS 2: k=1+2=3 PASS 3: k=3+2=5 PASS 4: k=5+2=7 PASS 5: k=7+2=9 can be +ve or –ve Default value is 1 for k=1:3:10 x = k^2 end x= 1 16 49 100 EXAMPLE LAST PASS: If s is +ve (<=) If s is –ve (>=) Number of passes is known ahead of time
  • 27. 28 Example Given an integer n, calculate the sum of the integers k2 for k = 1,...,n. The variable s is initialised to 0. The index variable k starts at 1, then increases in steps of 1 until it reaches n. Each time through the loop the value of k2 is added to s. Sol: s = 0; n=input('Enter the number of terms'); for k = 1:n s = s + k^2; end fprintf('The sum of the series is: %f','S')
  • 28. 29 CHAPTER 5 False A variable should be assigned the variable again must be assigned a new value x=1 while x<=15 x=2*x end EXAMPLE x = 1 x = 2 x = 4 x = 8 x = 16 stop the execution of an indefinite loop by pressing the Ctrl + C or Ctrl + Break keys. Indefinite loop Number of passes is NOT known in advance 3.5 Loops 3.5.2 while-end Loops
  • 29. 30 3.6 The Break and Continue Commands Write a program in a script file that finds the smallest odd integer that is dividable by 11 and whose square root is greater than 132. Use a loop in the program. The loop should start from 1 and stop when the number is found. The program prints the message “The required number is:” and then prints the number. for x=1:inf if rem(x,11)==0 & sqrt(x)>132 break else continue end end fprintf('n The required number is: %2.3f n',x) x=1; while true if rem(x,11)==0 & sqrt(x)>132 break end x=x+1; end fprintf('The required number is: %0.2f n',x)
  • 30. 31 CHAPTER FOUR EXAMPLE 1 Use a for-end loop in a script file to calculate the sum of the first n terms of the series: Execute the script file for n = 4 and n = 20. TIPS: 1. k=1 and n=4 & n=20 2. Use input command to enter n separately. 3. Define S=0; 4. Write for-end loop and enter the math expression in between. 5. (-1)^k*k/2^k 6. Use an output command to display the result S=0; n=input(‘Enter the number of terms’); for k=1:n; S=S+(-1)^k*k/2^k; end fprintf(‘The sum of the series is: %f',S)
  • 31. 32 EXAMPLE 2 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 dividable by 3 or 5, and, raises to the power of 3 the elements that are negative but greater than –5. TIPS: 1. Define vector V 2. Use for-end loop command, k=1, n=length(V) 3. If V elements are +ve & divisible by 3 or 5: make them double 4. If V elements are –ve & greater than -5: ^3 5. disp(V)

Editor's Notes

  • #9: Operand: the quantity on which an operation is to be done or performed
  • #17: wage