College of Natural and Computational Sciences
Lecture Note for:
Introduction to Mathematical Software
(Math3112)
By:Assefa Denekew
January 1, 2025
Chapter 3: Introduction to MATLAB
1.1 Getting started with MATLAB
q MATLAB, short form of MATrix LABoratory.
q It is a programming language, particularly suitable for numerical
computations with matrices and vectors.
q It can also display information graphically.
q Programs written for Matlab are called m-files because it takes the
extension .m.
Starting MATLAB
q To bring up MATLAB from the operating system you should
q click on the matlab icon or
q type matlab at command prompt
q This will present the MATLAB command window with prompt
2 / 53
Cont. . .
MATLAB Screen
q Command Window: used to type commands of the program.
q Workspace: used to view the program variable and value.
q Command history: used to view past commands and save a
whole session using diary.
3 / 53
Cont. . .
MATLAB Basics
Input and Output
q You put commands to MATLAB in the MATLAB Command
Window.
q MATLAB returns output in two ways:
q Typically, text or numerical output is returned in the same
Command Window,
q but graphical output appears in a separate graphics window.
q Variables are case sensitive, X is
different from x
=⇒
q The figure given below is an
example of output of ( 12 + 23 ) and
ezplot(0 x 3 − x 0 ).
4 / 53
Cont. . .
Arithmetic
Name Symbol Example: If a = 2, b = 4
Addition + a+b =6
Subtraction − a − b = −2
Multiplication ∗ a∗b =8
Right division / a/b = 0.5
Left division \ a\b = 2
Power aˆ b ab = 16
Special Constants Symbol Value
pi π 3.1416
Imaginary unit i 0.000 + 1.000i
Complex number z = 2 + 3i 2.000 + 3.000i
Modulus of z abs(z) 3.6056
Infinity ∞
5 / 53
Cont. . .
Built in functions
q Be ware of predefined variables like pi, i, j etc.
q String assignments −→w=’Mathematics 101’.
q MATLAB prints the answer and assigns the value called ans.
q Example:
3ˆ 2-(5+4)/2+6*9
ans=
58.5000.
q MATLAB assigns a new value to ans with each calculation.
q For example:
u=cos(10)
u=
-0.8391.
6 / 53
Cont. . .
There are three types of Number formats
Integer, Real and Complex.
q Non-Numbers Inf 1/0 and NaN 0/0.
q MATLAB uses double-precision floating point arithmetic, which is
accurate to approximately 15 digits; however, MATLAB displays
only 5 digits by default.
q To display more digits, type format long, then all subsequent
numerical output will have 15 digits displayed.
q Type format short to return to 5-digit display.
long format long
short format short
q If you make an error in an input line, MATLAB will beep and print
an error message.
7 / 53
Cont. . .
Example:
q 3uˆ 2
??? 3uˆ 2
|
Error: Missing operator, comma, or semicolon or Unexpected
MATLAB expression.
The error is a missing multiplication operator *. The correct input
would be 3*uˆ 2.
q Note that MATLAB places a marker (a vertical line segment) at the
place where it thinks the error might be;
q Missing multiplication operators and parentheses are among the
most common errors..
q You can edit an input line by using the UP Arrow key to re display
the previous command, editing the command using the LEFT and
RIGHT ARROW keys.
8 / 53
Cont. . .
Variables and Assignments
q In MATLAB, you use the equal sign to assign values to a variable.
q For instance:
x=7
x=
7
will give the variable x the value 7 from now on. Henceforth,
whenever MATLAB sees the letter x, it will substitute the value 7.
q For example: if y has been defined as a symbolic variable then
xˆ 2-2*x*y+y
ans =
49 − 13 ∗ y
q To clear the value of the variable x, type clear x.
9 / 53
Cont. . .
q You can make very general assignments for symbolic variables
and then manipulate them.
q For example:
clear x; syms x y
z=xˆ 2-2*x*y+y
z=
xˆ 2-2*x*y+y
5*x*z
ans=
5*y*(xˆ 2-2*x*y+y)
q A variable name or function name can be any string or letters,
digits, and under- scores. Provided, it begins with a letter
(punctuation marks are not allowed).
q MATLAB distinguishes between uppercase and lowercase letters.
10 / 53
Cont. . .
Solving Equations
q You can solve equations involving variables with solve or fzero.
q For example: To find the solutions of the quadratic equation
x 2 − 2x − 4 = 0, type
solve(’xˆ 2-2*x-4=0’)
ans =
[5ˆ (1/2)+1]
[1-5ˆ (1/2)]
q To get numerical solutions, type double(ans), or vpa(ans) to
display more digits.
q The command solve can solve higher-degree polynomial
equations, as well as many other types of equations.
11 / 53
Cont. . .
q It can also solve equations involving more than one variable.
q If there are fewer equations than variables, you should specify (as
strings) which variable(s) to solve for.
q For Example: Type solve(’2*x-log(y)=1’, ’y’) to solve
2x − logy = 1 for y interms of x.
q You can specify more than one equation as well.
q For example: Type
[x,y]=solve(’xˆ 2-y=2’, ’y-2*x=5’) and you will observe:
x= y=
[1+2*2ˆ (1/2)] [7+4*2ˆ (1/2)]
[1-2*2ˆ (1/2)] [7-4*2ˆ (1/2)]
q This system of equations has two solutions.
q MATLAB reports the solution by giving the two x values and the
two y values for those solutions.
12 / 53
Cont. . .
q Thus the first solution consists of the first value of x together with
the first value of y .
q You can extract these values by typing x(1) and y (1):
x(1)
ans =
1+2*2ˆ (1/2)
y(1)
ans =
7+4*2ˆ (1/2)
q Some equations cannot be solved symbolically, and in these
cases solve tries to find a numerical answer.
q For example: Type the following code and see its solution.
solve(’sin(x)=2-x’)
13 / 53
Cont. . .
Exercise:
1. Compute:
a) 1111 − 345
b) e14 and 382801π to 15 digits each. Which is bigger.
c) the fractions 2709/1024, 10583/4000 and 2024/765.
√
Which of these are the best approximation to 7?
2. Compute to 15 digits:
a) cosh(0.1)
b) arctan(1/2).
c) ln(2)
3. Solve the following equations:
a) 8x + 3 = 0
b) x 3 + px + q.
14 / 53
Cont. . .
1.2 MATLAB functions
Built-in functions
q In MATLAB you will use both built-in functions as well as
functions that you create yourself.
q MATLAB has many built-in functions.
q These include sqrt, cos, sin, tan, log, exp, and atan (for arctan) as
well as more specialized mathematical functions such as gamma,
erf, and besselj.
q MATLAB also has several built-in constants,
√ including pi (the
number π), i (the complex number i = −1), and Inf (infinity ∞).
q Here are some Example:
log(exp(3)) sin(2*pi/3)
ans= ans=
3 0.8660
15 / 53
Cont. . .
Note that:
q The function log is the natural logarithm, called ln in many texts.
q The above examples return approximate numeric solution.
q To get exact answer, you need to use a symbolic argument as
follows:
sin(sym(2*pi/3))
ans=
1/2*3ˆ (1/2)
User-defined function
q In this section we will show how to use "inline" to define your own
functions.
q Now let’s define the polynomial function f (x) = x 2 + x + 1:
16 / 53
Cont. . .
Inline function:
1. f=inline(’xˆ 2+x+1’,’x’)
f=
Inline function:
f(x) = xˆ 2+x+1
q The first argument to inline is a string containing the expression
defining the function.
q The second is a string specifying the independent variable.
q Once the function is defined, you can evaluate it as:
f(4)
ans =
21
2. Write these codes and evaluate:
a) f1=inline(vectorize(’xˆ 2+x+1’),’x’), f1(1:3)=?
b) g=inline(’uˆ 2+vˆ 2’,’u’,’v’), g(1,2)=?
17 / 53
Cont. . .
1.3 Plotting
2-D plotting
q MATLAB’s basic plotting commands are ezplot and plot.
q The simplest way to draw the graph of a function of one variable is
with ezplot, which expects a string or a symbolic expression
representing the function to be plotted.
q For example: To draw the graph x 2 + x + 1 on the interval -2 to 2
(using the string form of ezplot), type
ezplot(’xˆ 2 + x + 1’ , [-2 2]) =⇒
18 / 53
Cont. . .
Title and label
q We can add title of the graph and axis labeling as follows:
ezplot(’xˆ 2 + x + 1’ , [-2 2])
title (’A Parabola’)
=⇒
xlabel (’x-axis’)
ylabel (’y-axis’)
19 / 53
Cont. . .
q The command plot works on vectors of numerical data.
q The basic syntax is plot(X, Y) where X and Y are vectors of the
same length.
q The command plot(X, Y) considers the vectors X and Y to be lists
of the x and y coordinates of successive points on a graph and
joins the points with line segments.
q For example: To plot x 2 + x + 1 and y = sin(x) on the interval
from -2 to 2 and 0 to 2π we first make a list X of x values, and then
type
X= -2:0.1:2; plot(x, y)
plot(X, X.ˆ 2+X+1) xlabel(’x=0:π/2’)
X=0:π/100:2π; ylabel(’Sine of x’)
y=sin(x); title(’Plot of the sine function’)
20 / 53
Cont. . .
q You can choose the color of the graph: Possible to have more than
one graph together:
x=0:π/100:2π;
y=sin(x); z=cos(x);
plot(x,y,’r’,x,z,’g’)
legend(’sin(x)’,’cos(x)’)
grid on =⇒
xlabel(’x=0:π/2’)
ylabel(’function’)
title(’Plot of the Sine and
Cose functions’)
21 / 53
Cont. . .
Parametric Plots
q Sometimes x and y are both given as functions of some
parameter.
q For example: The circle of radius 1 centered at (0,0) can be
expressed in parametric form as x = cos(2πt); y = sin(2πt)
where t runs from 0 to 1.
q Though y is not expressed as a function of x, you can easily draw
this curve with plot, as follows:
t=0:0.01:1;
plot(cos(2*pi*t), sin(2*pi*t)) =⇒
axis square
22 / 53
Cont. . .
Contour Plots
q Contour plot of a function of two variables is a plot of the level
curves of the function,
q That is, sets of points in the x − y plane where the function
assumes a constant value.
q The command meshgrid produces a grid of points in a specified
rectangular region, with a specified spacing.
q a contour of x 2 + y 2 plotted as follows:
[X Y]=meshgrid(-3:0.1:3,-3:0.1:3);
contour(X, Y, X. ˆ 2 + Y. ˆ 2) =⇒
axis square
23 / 53
Cont. . .
3-D Plotting
Curves in Three-Dimensional Spaces
q For plotting curves in 3-space, the basic command is plot3,
q It works like plot, except that it takes three vectors instead of two,
one for the x coordinates, one for the y coordinates, and one for
the z coordinates.
Surfaces in Three-Dimensional Space
q There are two basic commands for plotting surfaces in 3-space:
mesh and surf.
q The former produces a transparent "mesh" surface; the latter
produces an opaque shaded one.
24 / 53
Cont. . .
For example:
q We can plot a Helix with
T=-2:0.01:2;
=⇒
plot3(cos(2*π*T), sin(2*π*T), T)
q We can plot a graph of z = x 2 − y 2 as:
[X, Y] = meshgrid(-2:0.1:2,-2:0.1:2);
Z=X.ˆ 2-Y.ˆ 2; =⇒
mesh(X, Y, Z)
25 / 53
Cont. . .
Exercise:
1. Use plot and/or ezplot, as appropriate, to draw the graph of the
following functions:
a) y = x 3 − x for − 4 ≤ x ≤ 4.
b) y = sin(1/x 2 ) for − 2 ≤ x ≤ 2.
c) y = tan(x/2) for − π ≤ x ≤ π, −10 ≤ y ≤ 10.
2. Use contour to plot the following:
a) f (x, y ) = 3y + y 3 − x 3 for − 1 ≤ x, y ≤ 1.
b) f (x, y ) = ylnx − xlny for − 1 ≤ x, y ≤ 1.
3. Plot the following surfaces:
a) z = sinxsiny for − 3π ≤ x, y ≤ 3π.
b) z = (x 2 + y 2 )cos(x 2 + y 2 ) for − 1 ≤ x, y ≤ 1.
26 / 53
Cont. . .
1.4 M-Files
q M-Files are ordinary text files containing MATLAB commands.
q you can use the built-in Editor/Debugger, which you can start by
typing edit, either by itself (to edit a new file) or followed by the
name of an existing M-file in the current working directory.
q You can also use the File menu or the two leftmost buttons on the
tool bar to start the Editor/Debugger, either to create a new file or
to open an existing file.
q There are two different kinds of M-files: script M-files and
function M-files.
Script M-Files
q We now show how to construct a script M-file to solve the
mathematical problem.
27 / 53
Cont. . .
For example:
q Create a file containing the following lines:
format long
x = [0.1,0.01,0.001];
y = sin(x)./x
q We will assume that you have saved this file with the name
task1.m in your working directory, or in some directory on your
path.
q You can tell MATLAB to run (or execute) this script by typing task1
in the Command Window as:
task1
y=
0.998334166468282 0.999983333416666
0.999999833333342
28 / 53
Cont. . .
q To revert to 5-digit format, you would have to type format short.
q Type
format short
x = [0.1,0.01,0.001];
y = sin(x)./x
Run and see the change from the previous
q If you want the commands to be displayed along with the results,
use echo:
q Type
echo on
format short
x = [0.1,0.01,0.001];
y = sin(x)./x
echo on Run and see the change from the previous result.
29 / 53
Cont. . .
Example:
q The radius of a circle is input through the keyboard. Write a
program to calculate the area and circumference of a circle.
Answer:
r=input(’Enter radius of a circle:’)
a = pi*rˆ 2;
c = 2*pi*r;
fprintf(’The area of a circle = %2.5f/n’,a)
fprintf(’The circumference of a circle = %2.5f/n’,c)
q Exercise:
Monthly salary is an input variable through the keyboard. Write a
program to calculate a 10% income tax payment from the monthly
salary.
30 / 53
Cont. . .
Function M-Files
q MATLAB allows you to define your own function by constructing
m-file in the m-file Editor. The first line of the function has the form
q function y = function_name(input argument)
q Example: To define the function f (x) = x 2 − 2x − 3 as an m-file:
q Type in the editor
function y = myfun1(x)
y = x.ˆ 2 - 2*x - 3; and save it as myfun1
q Once the function is saved in m-file named myfun1.m, you can
use it like the built-in functions to compute or plot.
myfun1(5)
ans =
12
31 / 53
Cont. . .
q Matlab can be used to find a zero of a function if it crosses x-axis:
q fzero(‘fun’, x_0)
finds a zero of function myfun1 closest to x_0.
q fzero(‘myfun1’, [a,b])
finds a zero of myfun1 in the interval [a, b].
q For instance:
x1=fzero(’myfun1’ , 0)
x1 =
-1
x2=fzero(’myfun1’ , [1, 5])
x2 =
3
q Built-in function quad(‘f’, a, b) produces numerical integration of
the function f(x) from a to b.
32 / 53
Cont. . .
Example:
q quad(’myfun1’,0,5)
ans =
1.6667
q Matlab can be used to find minima of a function on an interval:
x=fminbnd(’myfun1’,a,b)
finds a local minimizer x of the function myfun1 in the interval
a ≤ x ≤ b.
q Example:
x=fminbnd(’myfun1’,0,5)
x=
1
33 / 53
Cont. . .
Function of several variables
q For instance: For f (x, y ) = x 2 + y 2 you may define as:
function f=myfun2(x,y)
f = x.ˆ 2+y.ˆ 2
q Once this is saved at m-file named myfun2.m, you can use it like
any built in function.
q For instance, see the results of the following commands:
myfun2(2,3)
x = [0:5]; y=x+1; myfun2(x,y)
[x, y] = meshgrid(-3:0.2:3,-3:0.2:3);
surf(x, y, ,myfun2(x, y))
q To find a minimum of function of several variables, f(x), where
x ∈ R n , use the fminsearch command:
34 / 53
Cont. . .
Syntax of Conditions, and Loops
I) Conditional II) For loop:
if (expression 1) for index=initial:step:final
statment1 statements
elseif (expression 2) end
statment2 III) While loop:
else while (expression)
statment3 statements
end end
q Example: Write the following program and see the result.
x=input(’Enter any number:’)
if a<6
fprintf(’Wel come\n’)
else fprintf(’Good Bye\n’) end
35 / 53
Cont. . .
Examples:
q Write the following programs and execute:
1. The program to find the sum of the first 50 natural numbers:
sum=0;
for i=1:50
sum=sum+i;
end
fprintf(’The sum is=%d\n’,sum)
2. The program to displays integers 1 up to 10:
i=1;
while i<=10
fprintf(’%d\n’,i)
i=i+1;
end
36 / 53
Cont. . .
Exercise:
1. Write a program to find the factorial value of any number entered
through the keyboard.
2. Write a program that displays the first 100 natural numbers that
are not multiple of 2.
3. Write a program that displays the first 100 natural numbers that
are not multiple of 2 and not multiple of 5.
4. Write a program to display the reverse of any number.
5. Write a program to display:
a) * * * * * b) * * * * *
* * * * * * * *
* * * * * *
* * * *
* *
37 / 53
Cont. . .
1.5 Control structures
Programming in MATLAB
q Program in MATLAB consists of a sequence of MATLAB
commands and may include the following important flow control
commands.
q Example: Given the coefficients a, b, c of a quadratic function
f (x) = ax 2 + bx + c, write a Matlab program that
q checks the sign of the discriminant of the quadratic equation
q tells whether it has two real roots, one real root or complex
q finds the roots of the quadratic equation
P100 √
q Write a Matlab program to find the sum y = i=1 1/ i
q Write a Matlab program to identify the minimum of two numbers
by accepting from the keyboard.
38 / 53
Cont. . .
1.6 Matrix computation
Matrix syntax
x = [1 2 3 4]
x = (1, 2, 3, 4) x=
1 2 3 4
A = [1 2 3; 5 1 4; 3 2 − 1]
Matrix A = 3 × 3
A=
with row
1 2 3
1, 2, 3; 5, 1, 4;
5 1 4
and 3, 2, −1
3 2 -1
B=A T
B=
Transpose B = AT 1 5 3
2 1 2
3 4 -1
39 / 53
Cont. . .
Generating Matrices
m × n matrix of uniformly x = rand(1, 3)
rand (m, n) distributed random x=
numbers in (0, 1) 0.9501 0.2311 0.6068
x = zeros(2, 3)
x=
zeros (m, n) m × n matrix of zeros
0 0 0
0 0 0
x = ones(1, 3)
ones(m, n) m × n matrix of ones x=
1 1 1
x = eye(2, 2)
eye(n, n) m × n matrix of ones x=
1 0
0 1
40 / 53
Cont. . .
Generating Arrays
q The most useful commands are
q length(x) length of the array (number of its elements)
q norm(x) vector norm
q det(A) determinant of A.
q inv (A) inverse of A.
q eige(A) eigenvalues and eigenvectors of A.
q D=eig(A) vector containing the eigenvalues of A
q [V, D]=eig(A) yields a diagonal matrix D of eigenvalues and a
matrix V whose columns are the corresponding eigenvectors.
q rank(A) rank of A.
q lu(A) LU decomposition of A.
q qr(A) QR factorization of A.
q sum(A) sum of its elements of A.
q max(A) largest element of A.
q min(A) smallest element of A.
q mean(A) average of A.
q std(A) standard deviation of A.
41 / 53
Cont. . .
Subscripts and extraction of components
q After we created a matrix we might want to extract some elements
from it. To extract the i th element of a vector x you type
x(i) x(i : j) extracts the entries (components) of x from i to j.
Given a matrix A, A(i, j) extract its elements at i − j th entry.
q Typing the command:
q A(:, j) will extract the j-th column of A,
q A(i, :) will extract the i-th row of A, and
q diag(A) will extract the elements in the main diagonal of A.
Arithmetic operations on vectors/Matrices
q For matrices A and B.
symbol name code
+ addition A+B
− subtraction A−B
42 / 53
Cont. . .
symbol name code
∗ multiplication A ∗ B, k ∗ A for k ∈ R
/ right division A/B = A ∗ inv (B)
\ left division A\B = inv (A) ∗ B
ˆ power (A square matrix)r Aˆ 2=A*A
√
square root \sqrt(V)
.∗ element by element multiplication A. ∗ B
./ element by element right division A./B
.ˆ element by element power A.ˆ n
q Solution of System of Linear Equations Ax = b
q Enter the coefficient matrix A, column vector b, and check for
det(A)
q The command x = inv (A) ∗ b produces the solution.
43 / 53
Cont. . .
Relational and Logical operations
q Relational and operations
q == Equal
q ∼ = Not equal q Logical operations
q < Less than q & AND
q <= Less than or equal q | OR
q > Greater than q ∼ NOT
q >= Greater than or equal
44 / 53
Cont. . .
Examples
q Consider A = pascal(5)
A=
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
q Type the following command and see the result:
1. A>=5
2. sum(A>=5)
q Furthermore, consider the followings and explain the results:
1. (A>=5).*A 3. (A>5 & A<=20).*A
2. A>=5 & A<=20 4. length(A(A==10))
45 / 53
Cont. . .
1.7 Symbolic Mathematics
Differentiation
q You can use diff to differentiate symbolic expressions and also to
approximate the derivative of a function given numerically (say by
an M-file)
q syms x; diff(xˆ 3)
ans =
3*xˆ 2
q f = inline(’xˆ 2’, ’x’); diff(f(x))
ans =
3*xˆ 2
q To use the symbolic ODE solver on the differential equation
0
xy + 1 = y , you enter dsolve(‘x*Dy + 1 = y’, ‘x’)
46 / 53
Cont. . .
q The syntax for second derivatives is diff (f(x), 2),
q For nth derivatives, diff (f(x), n).
q The command diff can also compute partial derivatives of
expressions involving several variables, as in diff(xˆ 2*y,y)
q But to do multiple partials with respect to mixed variables you
must use diff repeatedly, as in diff (diff (sin(x*y/z), x), y).
q Remember to declare y and z symbolic.
Integration
q MATLAB can compute definite and indefinite integrals.
q Here is an indefinite integral:
47 / 53
Cont. . .
q int(’xˆ 2’,’x’)
ans =
1/3*xˆ 3
q As with diff, you can declare x to be symbolic and dispense with
the character string quotes.
q Note that MATLAB does not include a constant of integration; the
output is a single antiderivative of the integrand.
q Now here is a definite integral:
q syms x; int(asin(x),0,1)
ans =
1/2*pi-1
q MATLAB has different commands for numerical integration of a
function f(x) like: quad, quadl, etc.
48 / 53
Cont. . .
Examples
q syms x; int(xˆ 3*exp(-xˆ 4),0,1)
q quadl(vectorize( int(xˆ 3*exp(-xˆ 4)),0,1)
q MATLAB can also do multiple integrals.
q The following command computes the double integral
R π R sinx 2
0 0 (x + y 2 )dydx
q The Matlab code to compute the above double integral is:
syms x y; int(int(xˆ 2 + yˆ 2, y, 0, sin(x)), 0, pi) and it will
generate or it gives as
piˆ 2-33/9
49 / 53
Cont. . .
Limits
q You can use limit to compute right-handed and left-handed limits
and limits at infinity.
sin(x)
For example, lim can be coded as:
x→0 x
syms x; limit(sin(x)/x,x, 0)
ans =
1
q To compute one-sided limits, use the ‘right’ and ‘left’ options.
|x|
For example, lim can be coded as:
x→0 − x
syms x; limit(abs(x)/x,x, 0,’left’)
q Limits at infinity can be computed using the symbol Inf: Write the
x 4 +x 2 −3
code to compute lim 3x 4 −ln(x)
x→∞
50 / 53
Cont. . .
Sums and Products
q Finite numerical sums and products can be computed easily using
the vector capabilities of MATLAB and the commands sum and
prod. For example,
X = 1:7;
sum(X) prod(X)
ans = ans =
28 5040
q You can do finite and infinite symbolic sums using the command
symsum. To illustrate, here is the well-known infinite sum ∞ 1
P
n=1 n2 :
symsum(1/nˆ 2,1,Inf)
ans =
piˆ 2/6
51 / 53
Cont. . .
q AnotherP familiar example is the sum of the infinite geometric
series: ∞ n
n=0 a syms a n; symsum(aˆ n,0,Inf)
ans =
-1/(a-1)
q Note that: however, the answer is valid only for |a| < 1.
52 / 53
End of Chapter Three