DTU UG Mathematical Software 3
DTU UG Mathematical Software 3
By:Assefa Denekew
January 1, 2025
Chapter 3: Introduction to MATLAB
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.
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. . .
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. . .
9 / 53
Cont. . .
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. . .
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. . .
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
18 / 53
Cont. . .
19 / 53
Cont. . .
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.
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)
[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. . .
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. . .
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. . .
34 / 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. . .
38 / 53
Cont. . .
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. . .
42 / 53
Cont. . .
43 / 53
Cont. . .
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. . .
46 / 53
Cont. . .
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. . .
51 / 53
Cont. . .
52 / 53
End of Chapter Three