An Introduction to Matlab
Fellek Sabir (PhD)
Department Of Mathematics
Arba Minch University
March 21, 2025
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 1 / 71
outline
1 MATLAB Basics
2 Graphs:2d/3d plotting
3 Programming in MATLAB
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 2 / 71
[Link] Basics
Basics of Matlab
MATLAB is a general-purpose mathematical software
It is particularly suitable for doing numerical computations with
matrices and vectors.
( MATLAB : Matrix Laboratory )
It is possible to write computer programs in MATLAB and implement
it to solve problems of interest.
It can also display information graphically.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 3 / 71
Getting Started
Getting Started
To bring up MATLAB from the operating system you should
Double click on the matlab icon (MATLAB Logo)
(If the software is installed on your computer).
This will present the MATLAB command window with prompt
>>
If this appeared, you are in MATLAB window.
To exit out of the MATLAB use one of the following commands
>> exit or >> quit
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 4 / 71
Matlab Desk top
Matlab Desk top
When you start MATLAB, a special window called the MATLAB desktop
appears. The desktop is a window that contains other windows. The
major tools within or accessible from the desktop are:
The Command Window
The Command History
The Workspace
The Current Directory
The Help Browser
The default Matlab desk top display is shown in next slide.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 5 / 71
Default Matlab desk top display
Figure
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 6 / 71
Matlab Window
window purpose
Command window Main window, enters variables,
runs programs
Figure window Contains output from graphic commands
Editor window Creates and debugs script and function
files
Help window Provides help information
Command history window Logs commands entered in the
command window
Work space window Provides information about the variables
that are stored
current folder window Shows the files in the current folder
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 7 / 71
Matlab windows
Command windowIn the command window you can enter
commands and data, make calculations, and print results. You can
write a program (or script) in the command window and execute the
program. However, it will not be saved. Thus, if an error is made, the
entire program needs to be retyped. By clicking the up (↑) arrow key
on your keyboard the previous command can be reentered.
Command history window This window lists commands that the
user has used in the command window.
Current directory window This small window lists the current
working directory. To run a MATLAB program, the program needs to
be in the directory listed in this window. The directory listed in this
window can be changed by clicking on the little box just to the right
of the window. This produces a drop-down menu allowing one to
select the directory in which the program
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 8 / 71
Matlab windows
resides. If the working directory is not listed in the drop-down menu, one
can click on the little box containing the three dots, which allows one to
browse for the directory containing the program of interest.
Workspace window The workspace contains variables that you
create or import into MATLAB from data files or other programs.
You can view and edit the contents of the workspace in the
Workspace browser or in the Command Window. ... Workspace
variables do not persist after you exit MATLAB.
Editor window Programs are best written in the editor window.
Programs are then saved as m files. These files have the extension m,
such as heat.m. To execute the program, return to the command
window and type in the name of the program without the extension
(.m). The editor window can be obtained by clicking on File in the
task bar section and selecting New-M-file.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 9 / 71
Arithmetic Operations
You can perform arithmetic operations (+, −, ∗,ˆ) as in a calculator
and more. For instance, see
V
2
5 + 2, 5 − 2, 5 ∗ 2, 5
/ = right division
Two types of division:
\ = left division
≫ 4/2, 4\2, (ans = 2, 0.50)
Brackets , (V ), manage the order of operation as [Link]:
≫ ((5 + 3) 2 − (2 ∗ 2))/6, (ans = 10)
√
Complex numbers: MATLAB knows that i = −1. Exa.:
≫ (5 + 3i) − (2 − i) (ans = 3 + 4i)
≫ i ∗ (5 + 3i) (ans = −3 + 5i)
≫ (10 + 15i)/(3 + 4i) (ans = 3.6 + 0.2i)
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 10 / 71
Order of precedence
It is important to note the order in which algebraic expressions are
calculated. This is called the order of precedence, or the order of
operations.
As you probably expect, multiplication and division are calculated
before any addition or subtraction.
In general, the order of precedence is
1. parenthesis
2. exponentiation
3. multiplication,division
4. addition, subtraction
If the list is not enough to determine the order in which to calculate
an expression,the calculations are done from left to right.
For example, if you enter ≫ 10/20/10, Matlab first calculates
10/20=0.5, and then 0.5/10=0.05.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 11 / 71
Format:
Set output format, i.e., the way numbers appear
format short 4 digits after decimal point.
format long 15 digits after decimal point.
format bank 2 digits after decimal point.
format rat Approximation by ratio of integers (fraction).
format Default. Same as short.
Examples:
≫ format short;
≫ 1/2 2/3 ans=0.5000 0.6667
≫ format long;
≫ 1/2 2/3 ans=0.500000000000000 0.666666666666667
≫ format bank;
≫ 1/2 2/3 ans=0.50 0.67
≫ format rat;
≫ 1/2 2/3 ans=1/2 2/3
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 12 / 71
Built-in functions
MATLAB contains several built-in functions such as,
sqrt, sin, cos, exp, log, abs etc.
Example: Consider the following
sqrt(9) ans=3 sin(pi/2) ans =1
exp(1) ans=2.7183 log(exp(2)) ans=2
abs(-5) ans=5
To see the list of more built-in elementary functions , type
≫ help elfun
For instance: rem, floor, ceil, round, etc.
For a list of other special functions , type
≫ help specfun
For instance: factor, gcd, lcm, factorial, etc.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 13 / 71
Variables and assignment
A variable,such as x, x0, x1 , a, etc, is a storage object (container) of a
[Link] instance, consider the following
≫ a=5 ≫ b=11
a= b=
5 11
≫ c = a∧ 2 + b (you get c=36)
≫ c = sqrt(a + b) (you get c=4)
Note that the previous value of c is replaced (overwritten)
You can free (empty) a variable , say b, holding a value by the
command ”≫ clear b”
If you want to free all the variables that hold values, use the
command ”≫ clear”
MATLAB is case sensitive. That is, for instance, a and A are different
things for MATLAB
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 14 / 71
Vectors
A vector is a row or column of elements.
A row vector
In a row vector elements are entered with a space or a comma
between the elements inside the square brackets.
x=(1 2 5 1) Matlab syntax
≫ x=[1 2 5 1];
x=
1251
To extract i-th component of ≫ x3=x(3)
vector x, type x(i) x3=
5
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 15 / 71
Vectors continued
A column vector
In a column vector elements are entered with
a semicolon
between the
1
A= 5 ≫ A = [1; 5; 3]
3
elements inside the square brackets. A=
1
5
3
To extract i to j components of ≫ a=A(2:3)
vector A, type A(i:j) a=
5
3
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 16 / 71
Matrix
A matrix is entered row-wise with consecutive elements of a row
separated by a space or a comma,and the rows separated by
semicolons inside the square brackets.
1 2 3
A = 5 1 4 ≫ A=[1 2 3;5 1 4;3 2 -1]
3 2 -1
A=
1 2 3
5 1 4
3 2 -1
Transpose ≫ B = A′
B = AT B=
1 5 3
2 1 2
3 4 -1
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 17 / 71
Extracting part of a matrix
i-j entry of matrix A ≫ Ai j = A(1, 2)
Aij = A(i, j) Aij =
2
To extract i th row of A ≫ A2 = A(2, :)
Ai = A(i, :) A2=
5 1 4
To extract j th column of A ≫ A3 = A(:, 3)
Aj = A(:, j) A3=
3
4
-1
To extract all rows & columns a to b of A command is
≫ A(:,a:b)
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 18 / 71
Generating Some Matrices
rand(m,n) mxn matrix of uniformly ≫x=rand(1,3)
distributed random x=
numbers in (0,1) 0.9501 0.2311 0.6068
zeros(m,n) mxn matrix of zeros ≫x=zeros(2,3)
x=
0 0 0
0 0 0
ones(m,n) mxn matrix of ones ≫x=ones(1,3)
x=
1 1 1
eye(n,n) nxn identity matrix ≫x=eye(2,2)
x=
1 0
0 1
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 19 / 71
Some more Matlab comands for a given matrix A
The following aremore MatLab commands for a given matrix A:
Command Result
det(A) determinant of A
inv(A) inverse of A
D = eig(A) vector D containing the eigenvalues of A
[V , D]=eig(A) matrix V whose columns are eigenvectors
of A and diagonal matrix D of
corresponding eigenvalues
length(A) Returns the largest dimension of A.
numel(A) Returns number of elements of A .
[m,n] = size(A) Returns the dimensions of A.
A = diag(x) Creates a diagonal matrix A of x .
x = diag(A) Extracts diagonal elements from A.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 20 / 71
Some Commands on vectors
Given a vector x the following commands are useful:
length(x) number of elements (components) of x
norm(x) vector norm, ∥x∥
sum(x) sum of its elements
max(x) largest element of x
min(x) smallest element of x
mean(x) average or mean value
sort(x) sort (list) in ascending order
scalar and vector product of two vectors A & B:
dot(A,B) Scalar product of A and B.
cross(A,B) vector product of A and B
Example: Consider: ≫ A = [6, −3, 9, 5]; B = [3, 2, 5, 0]
≫ c = dot(A, B) ( c = 57 )
≫ m = max(A) ( m= 9)
≫ [m, i] = max(A) (m=9,i=3)i.e.,3rd variable i is the index of max e
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 21 / 71
Vectors/ Matrix as input of built-in functions
Consider ≫ x = [6, pi, 25, 0]
≫ A = [4, 25, 0; 1, 16, 2]
Then,
≫ a = sqrt(x), b = sqrt(A)
a=
2.4495 1.7725 5.0000 0
b=
2.0000 5.0000 0
1.0000 4.0000 1.4142
See also,
≫ sin(x), sin(A)
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 22 / 71
Operations on Vectors / Matrices A, B
+ addition As usual A+B ( Also k + A for k ∈ R)
- subtraction As usual A-B (Also A − k for k ∈ R
* Multiplication As usual A*B (Also k ∗ A for k ∈ R
/ right division A/B = A ∗ inv (B) (if B is invertible)
\ left division A\B = inv (A) ∗ B (if A is invertible)
∧ power A∧ 2 = A ∗ A ( A square matrix)
.* Element-by-element Multiplication A.*B
./ Element-by-element right division A./B
.∧ Element-by-element power A.∧ n
Example: Consider
≫ A = [6, 12, 10]; B = [3, 2, 5], then
≫ A. ∗ B ans=[ 18 24 50 ]
≫ A./B ans=[ 2 6 2 ]
∧
≫ A. B ans=[ 216 144 100000 ]
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 23 / 71
Generating Arrays/Vectors
One can define an array with a particular structure using the
command: a:step:b
x =1:0.5:3
x=
1 1.5 2 2.5 3
If step is not given, Matlab takes 1 for it.
x =-2:4
x=
-2 -1 0 1 2 3 4
linspace(a, b, n) generates a row vector of n equally
Example:
spaced points between a and b.
≫ x = linspace(1, 10, 4) ( ans x = [1, 4, 7, 10])
linspace(a, b) generates a row vector of 100 equally
spaced points between a and b.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 24 / 71
Polynomials
MATLAB provides a number of useful commands that operates on
polynomials: p(x) = an x n + an−1 x n−1 + · · · + a2 x 2 + a1 x + a0 .
A polynomial of degree n is specified by writing its coefficients as the
entries of a vector with n+1 components:
p=[ an an−1 · · · a2 a1 a0 ]
For instance, the polynomial p(x) = 2x 3 − 5x 2 + 8 is specified by
≫ p = [2, −5, 0, 8]
polyval (p, x0 ) evaluates the polynomial p at x0 , i.e., p(x0 ).
Example: ≫ polyval(p, 2) (ans = 4)
roots(p) finds all roots of the polynomial p. For example,
≫ roots(p) ans=
1.7800 + 0.7779i
1.7800 - 0.7779i
-1.0600
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 25 / 71
Solution of System of Linear Equations Ax = b
Solution of Ax = b is given by x = A−1 b if inverse of A exists.
So we need to check that det(A) ̸= 0 & then use x = A−1 b.
Thus, to solve a system of n × n linear equations Ax = b using
matlab :
enter
the coefficient matrix A
column vector b,and
check for det(A)
If det(A) ̸= 0 the command x = inv (A) ∗ b produces the solution.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 26 / 71
Useful Built in Functions
MATLAB has several useful built in functions (commands) that can
be used to solve various problems directly. For example:
fzero : Finds a zero (root) of a function f if it crosses the x-axis:
syntax fzero(′ f ′ , x0 ) finds a zero of function f closest to x0 .
fzero(′ f ′ , [a, b]) finds a zero of f in the interval [a, b].
minbnd : Finds a minimum point of a function on a given interval [a,
b].
Syntax: fminbnd(’f’,a,b )
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 27 / 71
[Link]
2d plotting
≫ x = 0 : 0.01 : 2 ∗ pi;
y = sin(x);
plot(x,y),grid on
xlabel(’x = 0: 2π’)
ylabel(’Sine of x’ )
title(’Plot of the Sine Function’)
You can choose the color of the graph:
≫ x = 0 : 0.01 : 2 ∗ pi;y = sin(x); plot(x,y,’r’),grid on
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 28 / 71
2d plotting continuation
It is possible to have more than one graph together:
≫ t = 0: 0.01: 2*pi;
y1 = sin(t); y2 = cos(t);
plot( t , y1, t, y2 );
legend(’sint’, ’cost’ ), grid on
Figure: Plot of sine and cosine functions
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 29 / 71
2d plotting continuation
The basic command for producing a simple 2-D plot is plot(x values, y
values, ’style option’)where x values and y values are vectors containing
the x- and y-coordinates of points on the [Link] option is an optional
argument that specifies the color, line-style and the point-marker style.
Points at which a function is evaluated can be generated also by
linspace.
linspace(a, b, n) generates n equally spaced points from a to b.
Example: plot the polynomial y = x 4 − 6x 3 + 8x 2 − 5 on [−1, 4.5]
(using fifty points)
≫ x = linspace(−1, 4.5, 50) ;
f = [1, −6, 8, 0, −5]; % the given function is polynomial
y = polyval( f, x);
plot( x, y ); grid on (This produces the output shown next)
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 30 / 71
2d plotting continuation
Figure: Graph of y = x 4 − 6x 3 + 8x 2 − 5
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 31 / 71
2d plotting continuation
The style option in the plot command is a character string that
consists of 1, 2 or 3 characters that specify the color and/or the line
style. The different color, line-style and marker-style options are
summarized in Table below.
color style option Line style option Marker style option
y yellow - solid + plus sign
m magenta – dashed ◦ circle
c cyan : dotted ∗ asterisk
r red -. dash-dot x x-mark
g green s square
b blue d diamond
w white
k black
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 32 / 71
3d ploting
plot3(x,y,t)plots a parametrically given curve in 3-D, where
x=x(t),y=y(t),a ≤ t ≤ b
As an example consider the following:
≫ t= 0: 0.01: 37;
x=cos(t); y=sin(t);
plot3(x,y,t);
xlabel(’x’); ylabel(’y’); zlabel(’z’);
title(’Helix’)
output of this is shown in next slide
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 33 / 71
3d plotting continuation
Figure: plot of a 3d curve
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 34 / 71
[Link] in MATLAB
3.1 Basics in Matlab Programming
MATLAB is also a Programming Language. So, you can write your
own MATLAB program to solve a specific problem.
In Matlab, programs may be written and saved in files with a suffix
.m called [Link] M-file consists of a series of statements that can
be run all at once. Note that the nomenclature ”M-file” comes from
the fact that such files are stored with a .m extension. There are two
types of M-file programs: script files and function files.
ScriptFiles
A script file is a file that contains a sequence of MATLAB commands,
which is also called a program.
Using a script file is convenient because it can be stored, edited later
(corrected and/or changed), and executed many times.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 35 / 71
Script files can be typed and edited in any text editor and then pasted
into the MATLAB editor.
There are no input and output variables in script files.
Script files are created and edited in the Editor/Debugger Window.
Before a script file can be executed, it has to be saved. This is done
by choosing Save As · · · from the File menu, selecting a location
(folder), and entering a name for the file. The names of user-defined
variables, predefined variables, MATLAB commands, or functions
should not be used to name script files.
A script file can be executed either by typing its name in the
Command Window and then pressing the Enter key, or directly from
the Editor Window by clicking on the Run icon.
Input to a script file
When a script file is executed, the variables used in the calculations
within the file must have assigned values.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 36 / 71
INPUT-OUTPUT
The following functions provide ways to enter and display information
directly using the command window.
The input Function : This function allows you to prompt the user
for values directly from the command window. Its syntax is:
n = input(’promptstring’)
The function displays the promptstring, waits for keyboard input, and
then returns the value from the keyboard. For example,
m = input(’Mass (kg): ’)
When this line is executed, the user is prompted with the message
Mass (kg):
If the user enters a value, it would then be assigned to the variable m.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 37 / 71
The disp Function: This function provides a handy way to display
a value. Its syntax is:
disp(value)
where value = the value you would like to display. It can be a
numeric constant or variable, or a string message.
The fprintf Function: This function provides additional control over
the display of information. A simple representation of its syntax is:
fprintf(’format’, x, ...)
where format is a string specifying how you want the value of the
variable x to be displayed. The operation of this function is best
illustrated by examples.
A simple example would be to display a value along with a message.
For instance, suppose that the variable velocity has a value of
50.6175. To display the value using eight digits with four digits to the
right of the decimal point along with a message, the statement along
with the resulting output would be
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 38 / 71
fprintf(’The velocity is %8.4f m/s.\n’, velocity)
The velocity is 50.6175 m/s
This example should make it clear how the format string works. MATLAB
starts at the left end of the string and displays the labels until it detects
one of the symbols: % or \.
In our example, it first encounters a % and recognizes that the following
text is a format code. As in Table below, the format codes allow you to
specify whether numeric values are displayed in integer, decimal, or
scientific format. After displaying the value of velocity, MATLAB
continues displaying the character information (in our case the units: m/s)
until it detects the symbol \. This tells MATLAB that the following text is
a control code. As in table below, the control codes provide a means to
perform actions such as skipping to the next line. If we had omitted the
code \n in the previous example, the command prompt would appear at
the end of the label m/s rather than on the next line as would typically be
desired.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 39 / 71
Commonly used format and control codes employed with the fprintf
function.
Format code Description
%d Integer format
%f Decimal format
%e Scientific format
%g The more compact of %e or %f
Control code Description
%n Start new line
%t Tab
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 40 / 71
The fprintf function can also be used to display several values per line with
different formats. For example,
≫ fprintf(’%5d %10.3f %8.5e\n’,100,2*pi,pi);
100 6.283 3.14159e+000
It can also be used to display vectors and matrices. Here is an M-file that
enters two sets of values as vectors. These vectors are then combined into
a matrix, which is then displayed as a table with headings:
function fprintfdemo
x = [1 2 3 4 5];
y = [20.4 12.6 17.8 88.7 120.4]
z = [x;y];
fprintf(’ x y\n’);
fprintf(’%5d %10.3f\n’,z);
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 41 / 71
The assignment of a value to a variable can be done in three
ways,depending on where and how the variable is defined.
1. One option is to define the variable and assign it a value in the script
file. In this case the assignment of value to the variable is part of the
script file. If the user wants to run the file with a different variable
value, the file must be edited and the assignment of the variable
changed. Then, after the file is saved, it can be executed again.
2. A second option is to define the variable and assign it a value in the
Command Window. In this case, if the user wants to run the script file
with a different value for the variable, the new value is assigned in the
Command Window and the file is executed again.
3. The third option is to define the variable in the script file but assign a
specific value in the Command Window when the script file is executed.
This is done by using the input command.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 42 / 71
Program comments
For programs that have more than a couple of lines it is important to
include comments. Comments allow other people to know what your
program does and they also remind yourself what your program does
if you set it aside and come back to it later. It is best to include
comments not only at the top of a program, but also with each
section. In Matlab anything that comes in a line after a % is a
comment. For a script program it is often helpful to include the name
of the program at the beginning. For example:
Example 1: a=input(’enter first number a=
%script1.m ’);
a=2;b=4; b=input(’enter second number
c=(a+b)/2 b= ’);
Example 2: c=(a+b)/2;
% script2.m c
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 43 / 71
Function Files
Function files are M-files that start with the word function. In contrast
to script files, they can accept input arguments and return outputs.
The input arguments are listed inside parenthesis following the
function [Link] output arguments are listed inside brackets on the
left side.
The general form looks like:
function [outputs] = function name( inputs )
The word ”function”, typed in lower case letters, must be the first
word in the function definition line. The input and output arguments
are used to transfer data into and out of the function. Usually, there
is at least one input argument. If there are more than one, the input
arguments are separated by commas.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 44 / 71
The output arguments, which are listed inside brackets on the left
side of the assignment operator in the function definition line, transfer
the output from the function file. A user-defined function can have
one, several, or no output arguments. If there are more than one, the
output arguments are separated with commas or spaces. If there is
only one output argument, it can be typed without brackets. In order
for the user defined function to work, the output arguments must be
assigned values within the computer program of the function.
Following the function definition line, there are usually several lines of
[Link] are optional but frequently used to provide
information about the function. Next,the function contains the
computer program (code) that actually performs the computations.
The code can use all MATLAB programming features, including
calculations, assignments, any built-in or user-defined functions, and
flow control (conditional statements and loops; ).
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 45 / 71
Examples
Example 1:
To define the function f (x) = x 2 + 1 as an m-file :Type in the Editor
function f = myfun1(x);
f = x.∧ 2 + 1 ;
and save it as myfun1.
Once the script of the function is saved in m-file named myfun1.m,
you can use it like the built-in functions to compute. For instance,
≫ myfun1(2)
ans=
5
≫ z=myfun1(2)+3
z=
8
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 46 / 71
Functions continuation
See the effect of : ≫ x = [−2, −1, 0, 1, 2]; myfun1( x)
The output and input can be vector or scalar as desired.
For example, the following is a MATLAB program that takes certain
real numbers x1 , x2 , · · · , xn as in put vector X; and returns two vector
outputs Y and Z, where components Y are square root of
x1 , x2 , · · · , xn , and components Z are square of x1 , x2 , · · · , xn ,
respectively.
Example 2:
function [Y, Z ] = prog1(X) % This program is saved as prog1.m
Y = sqrt(X ); Z = X .∧ 2;
After saving this, say as prog1.m, you can run it just like a function:
≫ x = [0, 4, 9, 16]; [y , z] = prog 1(x)
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 47 / 71
Functions continuation
Built-in function quad(’f’, a, b ) produces numerical integration
Rb
(definite integral) of f(x) from a to b. i.e.,quad(′ f ′ , a, b) = a f (x)dx
≫ I = quad(′ myfun1′ , 0, 1) answer I= 1.3333
You can define also a function of several variables.
For instance,for f (x, y ) = x 2 + y 2 − 4x,you may define
function f = myfun2(x);
% x=x(1);y=x(2);
f = x(1).∧ 2 + x(2).∧ 2 − 4 ∗ x(1) ;
Once this is saved as, say, myfun2.m, you can use it like any built in
function. For example, see:
myfun2([0, 1]) , v = 10*myfun2([0, 1])
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 48 / 71
MATLAB program may not necessarily begin as a function if its input
is fixed and included in the internal part of the program.
For example,the following program does the same as prog1.m when
the input is fixed, say x = [0, 4, 9, 16].
% Program name [Link] program finds the square root
% and square of the components of x= [0, 4, 9, 16];
x = [0, 4, 9, 16];
y = sqrt(x);
z = x.∧ 2;
fprintf(’Square Root:y=(%3.4f,%3.4f,%3.4f,%3.4f) \ n’, y );
fprintf(’Square: z=(%5.0f, %5.0f, %5.0f,%5.0f) \n’, z );
Note: fprintf writes formatted data:
Here, a format %n.m f means, the output can have up to n digits
before decimal point and m digits after decimal point.
\ n is the line termination character (new line follows).
See also disp
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 49 / 71
Conditional Statements and Loops
A computer program is a sequence of computer commands. In a
simple program the commands are executed one after the other in the
order that they are typed. Many situations, however, require more
sophisticated programs in which different commands (or groups of
commands) are executed when the program is executed with different
input variables.
In other situations there might be a need to repeat a sequence of
commands several times within a program. For example,programs
that solve equations numerically repeat a sequence of calculations
until the error in the answer is smaller than some measure.
MATLAB provides several tools that can be used to control the flow
of a program. Conditional statements make it possible to skip
commands or to execute specific groups of commands in different
situations.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 50 / 71
For loops and while loops make it possible to repeat a sequence of
commands several times. Changing the flow of a program requires
some kind of decision making process within the program. The
computer must decide whether to execute the next command or to
skip one or more commands and continue at a different line in the
program.
The program makes these decisions by comparing values of variables.
This is done by using relational and logical operators.
Conditional statements are statements that are executed only if
certain conditions are [Link] they enable programs to make
decisions.
Operators that are used in conditional statements fall in one of the
two categories relational operators and logical operators.
Logical expressions evaluate to a value of true or false. This is a
different kind of information than a number, though MATLAB
represents a false with 0 and a true with 1. In fact, any nonzero value
is interpreted as a logical true.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 51 / 71
Relational Operators and Logical Operators
Relational Operators
Less than < (2 < 3is true and produces the output 1)
Less than or equal <= (5 <= 4 produces output 0)
Greater than > (−2 > −1 produces the output 0)
Greater than or equal >= (For example 2 >= 2 produces output 1)
Equal to == (There are two equality signs)
Not equal to ∼= (example 5 ∼= 5 produces the output 0).
Logical Operators
Not ∼ (For example ∼ (3 < 2) is true)
And & or && (For example (2 < 1)&&(5 > 4) is false)
Or | or ∥ (For example (2 < 1)∥(5 > 4) is true)
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 52 / 71
Conditional Structures
if expression 1
command
end
Example:
% program name evenodd.m
n = input(’Please enter an integer: ’);
if (rem(n,2)==0)
fprintf(’The integer %d is even.\n’, n)
end
Return to the command window and run the script by entering evenodd at
the Matlab prompt. Matlab responds by asking you to enter an integer.
As a response, enter the integer 12 and press Enter.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 53 / 71
≫ evenodd
Please enter an integer: 12
The integer 12 is even.
Run the program again. When prompted, enter the nonnegative integer 17
and press Enter.
≫ evenodd
Please enter an integer: 17
There is no response in this case, because our program provides no
alternative if the input is [Link] can provide an alternative if the logical
expression evaluates as false. The basic structure is as follows.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 54 / 71
if expression 1
command 1
else
command 2
end
In this form, if the logical expression 1 evaluates as true, the block of
statements between if and else are executed. If the logical expression
evaluates as false, then the block of statements between else and end are
executed.
Example:
n = input(’Please enter an integer: ’);% program name evenodd2.m
if (rem(n,2)==0)
fprintf(’The integer %d is even.\n’, n)
else
fprintf(’The integer %d is odd.\ n’, n)
end
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 55 / 71
Run the program, enter 17, and note that we now have a different
response.
≫ evenodd2
Please enter an integer: 17
The integer 17 is odd.
Because the logical expression rem(n,2)==0 evaluates as false when n =
17, the fprintf command that lies between else and end is executed,
informing us that the input is an odd integer.
Sometimes we need to add more than one alternative. For this, we have
the following structure.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 56 / 71
if expression 1
command 1
elseif expression 2
command 2
else
command 3
end
Program flow is as follows.
1. If logical expression 1 evaluates as true, then the block of statements
between if and elseif are executed.
2. If logical expression 1 evaluates as false, then program control is
passed to elseif. At that point, if logical expression 2 evaluates as
true, then the block of statements between elseif and else are
executed. If the logical expression 2 evaluates as false, then the block
of statments between else and end are executed.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 57 / 71
You can have more than one elseif in this control structure, depending on
need. As an example of use, consider a program that asks a user to make
a choice from a menu, then reacts accordingly.
First, ask for input, then set up a menu of choices with the following
commands.
a=input(’Enter a number a: ’);
b=input(’Enter a number b: ’);
fprintf(’\ n’)
fprintf(’1) Add a and b.\ n’)
fprintf(’2) Subtract b from a.\ n’)
fprintf(’3) Multiply a and b.\ n’)
fprintf(’4) Divide a by b.\ n’)
fprintf(’\ n’)
n=input(’Enter your choice: ’);
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 58 / 71
Now, execute the appropriate choice based on the user’s menu selection.
if n==1
fprintf(’The sum of %0.2f and %0.2f is %0.2f.\n’,a,b,a+b)
elseif n==2
fprintf(’The difference of %0.2f and %.2f is %.2f.\n’,a,b,a-b)
elseif n==3
fprintf(’The product of %.2f and %.2f is %.2f.\n’,a,b,a*b)
elseif n==4
fprintf(’The quotient of %.2f and %.2f is %.2f.\n’,a,b,a/b)
else
fprintf(’Not a valid choice.\n’)
end
Save this script as mymenu.m, then execute the command mymenu at the
command window prompt. You will be prompted to enter two numbers a
and b.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 59 / 71
As shown, we entered 15.637 for a and 28.4 for b. The program presents a
menu of choices and prompts us for a choice.
≫ mymenu
Enter a number a: 15.637
Enter a number b: 28.4
1). Add a and b.
2). Subtract b from a.
3). Multiply a and b.
4). Divide a by b.
Enter your choice:
We enter 1 as our choice and the program responds by adding the values
of a and b.
Enter your choice: 1
The sum of 15.64 and 28.40 is 44.04.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 60 / 71
Eample
Roots of a quadratic equation
Consider a quadratic equation
ax 2 + bx + c = 0
Write a Matlab program that
takes any real number a, b, c as input
checks the sign of the discriminant of the quadratic equation and
tells whether it has two real roots, one real root or complex root
finds the roots of the quadratic equation and returns the roots in r1
and r2.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 61 / 71
function rootquad(a,b,c)
% Finds the root of quadratic function f (x) = ax 2 + bx + c
D = b ∧ 2 − 4 ∗ a ∗ c; % D is its discriminant
if (D > 0)
r 1 = (−b + sqrt(D))/(2 ∗ a); r 2 = (−b − sqrt(D))/(2 ∗ a);
r=[r1, r2];
disp(’ It has two real roots: ’ ), r
elseif (D==0)
r = –b/(2 ∗ a);
disp(’It has one double root: ’ ), r
else
r 1 = (−b + sqrt(D))/(2 ∗ a) ;
r 2 = r 1′ ;
r=[r1, r2];
disp(’Has No real Root. Its complex roots are: ’ ) , r
end
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 62 / 71
Loops
A loop is a collection of commands that is repeated a certain number of
times. 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) that is
defined within the loop is assigned a new value.
For loop
A for loop is a repetition control structure that allows you to efficiently
write a loop that needs to execute a specific number of [Link] is its
general use syntax.
for index=start:increment:final
statements
end
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 63 / 71
As an example,we display the squares of every other integer from 5 to 13,
inclusive.
for k=5:2:13
fprintf(’The square of %d is %d.\n’,k,k 2 )
end
The output of this simple loop follows.
The square of 5 is 25.
The square of 7 is 49.
The square of 9 is 81.
The square of 11 is 121.
The square of 13 is 169.
Another looping construct is Matlab’s while structure.A for loop is a
count-controlled loop—the number of times the loop executes is
determined when the loop starts. There are situations where the number
of times you want the loop repeated is not known at the beginning.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 64 / 71
For example, you might want to repeat a block of statements until a
certain condition is met. This type of loop is called a ”condition
controlled” loop and is implemented in MATLAB using the while
command.
While loop
while expression
statements
end
The while loop executes its block of statements as long as the logical
controlling expression evaluates as true. For example, we can duplicate the
output of the previous for loop with the following while loop.
k=5;
while k <= 13
fprintf(’The square of %d is %d.\n’, k, k ∧ 2)
k=k+2;
end
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 65 / 71
When using while, it is not difficult to fall into a trap of programming a
loop that iterates indefinitely. In the example above, the loop will iterate
as long a k <= 13,so it is imperative that we increment the value of k in
the interior of the loop, as we do with the command k=k+2. This
command adds 2 to the current value of k, then replaces k with this
incremented value. Thus, the first time through the loop, k = 5, the
second time through the loop, k = 7, etc. When k is no longer less than or
equal to 13, the loop terminates.
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 66 / 71
Examples
Example 1
n
X
Write a for loop to compute z(n) = i 2 for a given number n.
i=1
Solution
function z= zsum(n)
s=0;
for i = 1:n
s = s + i 2;
end
z=s;
When we run this program we get the following result
≫ zsum(5)
ans =55
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 67 / 71
Example 2
You can nest for loops.
n
X
Use nested for loop to compute z(n) = i 2 and print out the result for
i=1
each natural number n =1 to 10.
Solution
% program name = zsumn.m
disp(′ n z(n)′ );
disp(′ − − − − − − −′ );
for n = 1:10
s=0;
for i = 1:n
s = s + i ∧ 2;
end
fprintf(’%2.0f %6.0f ,\n’, n,s);
end
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 68 / 71
Tabular Values
MATLAB can provide calculated values in tabular form
For instance, suppose we want to have the table of values for
y = log 10(x), where x = 0.5, 1, 1.5, 2, 2.5, · · · , 10
See the effect (output) of the following program:
disp(′ − − − − − − − − − − − − − − − − − − − − − − − − − − − − −′ )
disp(′ x y = log 10(x)′ ) % Heading of the table
disp( − − − − − − − − − − − − − − − − − − − − − − − − − − − − −′ )
′
for x=0.5:0.5:6
y=log10(x);
fprintf(’ %2.2f %12.6f \n’, x,y ) %print format
end
disp(′ − − − − − − − − − − − − − − − − − − − − − − − − −−′ )
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 69 / 71
The above program yields:
x y=log10(x)
0.50 -0.301030
1.00 0.000000
1.50 0.176091
2.00 0.301030
2.50 0.397940
3.00 0.477121
3.50 0.544068
4.00 0.602060
4.50 0.653213
5.00 0.698970
5.50 0.740363
6.00 0.778151
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 70 / 71
END
THANK YOU
Fellek Sabir (AMU, CNS) An Introduction to Matlab March 21, 2025 71 / 71