OPM Chapter 3 Element of Programmings
OPM Chapter 3 Element of Programmings
of Algiers 1
Faculty of Sciences, Department of Mathematics
Prepared by:
Dr KHETTABI Imen
Year: 2024-2025
Chapter 3:
Elements of programming
1.1 Reading data in a program (Inputs)
1.2 Writing data in a program (Outputs)
1.3 Script
1.4 Function
1.5 Control structure
1.5.1 Conditional Structure (if … elseif … else)
1.5.2 Multiple Conditional Structure (switch … case)
1.5.3 Conditional loop (while)
1.5.4 Iterative loop (for)
1.6 Creating and Running MATLAB Programs Using M-Files
9
Example:
10
Syntax:
disp(text or variable)
Example:
Example:
11
Syntax:
fprintf( format text, variables)
Example:
12
3.3 Script
A script is a program or a sequence of MATLAB instructions saved in a file
with the extension ".m".
3.4 Function
A function is a set of instructions grouped in a structure that allows it to
have input variables (the data) and output variables (the results).
Notes:
- The name of the function saved in a file with the ".m" extension must be
identical to the defined function name.
- The end of the function is optional.
- Do not name functions with hyphens, such as "vector-product".
- Do not name functions using multiple words separated by spaces, such as
"vectorproduct".
Example :
13
Syntax
if expression1
instructions1 …
elseif expression2
instructions2 …
else
instructions3 …
end
Example :
14
Switch expression
case value1,
instructions1 …
case value2,
instructions2 …
case value3,
instructions3 …
………
Otherwise instructions …
end
Example :
15
while expression
instructions …
end
Example1 :
This script uses a while loop to calculate the square of numbers from 1 to 5.
16
Example2 :
Compute the sum s = 1 + 2/2! + 3/3! + .... stop when s > 2.5
Syntax
Example 1 :
Example2 :
Example3 :
18