0% found this document useful (0 votes)
5 views25 pages

MATLAB Basics: Numerical Methods Guide

This document presents an introduction to using MATLAB software. It describes the basic commands for performing calculations and plotting graphs directly in the command window, as well as creating and executing programs stored in .m files.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views25 pages

MATLAB Basics: Numerical Methods Guide

This document presents an introduction to using MATLAB software. It describes the basic commands for performing calculations and plotting graphs directly in the command window, as well as creating and executing programs stored in .m files.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Democratic and Popular Algerian Republic

Ministry of Higher Education and Scientific Research


University of Tahri-Mohamed-Béchar

DEPARTMENT OF CIVIL AND HYDRAULIC ENGINEERING

TP Numerical Methods

Presented By:
ABDERAHMANE BOUCHETA

2019-2020
TP 1: Simple Examples to Start
to Use MATLAB

1. Introduction
2. First operations: Keyboard commands

3. Creating a program in a file


3.1. Find and run MATLAB programs written in '.m' files and
filed in a folder

4. Development and modification of a program

5. Operations in Matlab

6. Management of Graphs

Boucheta.A Page 1
1 Introduction
MATLAB is the abbreviation for MATrix LABoratory. It is an environment for
development in the field of numerical matrix calculations. This software is developed by
The company The MathWorks. The appeal of Matlab lies, on the one hand, in its ease of use:
no compilation, implicit declaration of used variables, and on the other hand, to its richness
functional: matrix arithmetic and many high-level functions in
numerous fields (numerical analysis, graphic, ...).
It is a multiplatform software, meaning it can be used under different
environments (operating systems), such as: Linux, Unix, Mac OS, and Windows.
MATLAB is proprietary software (not free). It can be used in different
fields such as physical sciences, signal processing, analysis and processing
images, numerical analysis, algebra in general, automation, industrial computing,
the command of systems, neural networks, fuzzy logic, symbolic computation,
aeronautics, etc. The official website of this software is: [Link].
MATLAB allows for the manipulation of arrays and matrices, displaying curves and
data, implementing algorithms, plotting graphs in two and three
dimensions, to solve equations and polynomials, etc. So the practical work of
MATLAB aims to master this tool which was very powerful and very usable.
for numerical computation and graphical visualization. The software MATLAB is built
around the MATLAB language. A command-line interface, which is one of the elements
From the MATLAB desk, it allows executing simple commands.

Image 1: The MATLAB logo

Boucheta.A Page 2
2 First operations: Keyboard commands (to perform simple calculations, a
graph displays, ...) in the command window

Indicate that Matlab is waiting for a command

Entry to
keyboard

The result
displays

Entry to
keyboard

The result is
calculated and displayed

Command to plot the sequence "b"


The graph will appear in another window
"grid on" indicates that the units appear
in the layout in the form of a grid
e

In this example, 'a' is a row vector; by typing 'b=a+2' you create a second vector.
line 'b' by adding 2 to each of the elements of 'a'

A plot is requested by hitting the command 'plot'; the result is displayed in a


new window: on the x-axis we obtain the index number and on the y-axis the value of the
corresponding component of 'b'.

Boucheta.A Page 3
Display in the
new window of
values of the elements of
the sequence b

If you hit a semicolon at the end of the command line

b = a + 2;

and no
b = a + 2

So the command is executed but the result is not displayed.

If we want to enter a long sequence of regular intervals without entering all the values, we
use the colon ':'

It is possible to apply functions on the sequence 'a':

Boucheta.A Page 4
display the sine of the sequence:

On the x-axis, there is a simple number: the position of element a in the calculation (it will be noted that
matlab starts the index numbers at 1 and not at zero)

To navigate through the list of instructions, you can use the arrow keys on the keyboard.

If you press 'Enter', the selected line will be executed.

3 Creation of program in a file

One realizes that directly entering instructions makes it difficult to generate without
error of very complex operation sequences; to achieve this, it is necessary to record the
programs in a file that will be executed when it is ready

Click on 'File' and (while holding down the index finger, left click) in the drop-down menu
«New» «M-File». This opens a new window (‘Editor’) in which one
edit the program text

Boucheta.A Page 5
Organization of
files in
the files

Attention: It is important to get accustomed to file management: one must know in which
file folder to organize files so that they can be found, modified if necessary and
execute afterwards. Once we have written a program, we need to save it: we choose
for example 'save as' and the file name must necessarily have the '.m' extension:
Matlab will subsequently recognize this extension when asked to execute in the
command window; for example, to execute the program saved in the file
"premierpas.m" you will need to hit in the "Command Window"

first step

Here the file 'premiersepas.m' is stored in the 'work' folder of MATLAB.

Boucheta.A Page 6
Here is the content of the file 'premierspas.m'

By hitting the command 'premierspas', we execute the program contained in the file.
firststep.m
The second command "plot(t,x)" plots the sequence x as a function of the sequence t:
instructions given in the command window recognize the
names of variables given in the program file: everything goes as if the sequence
the program's instructions were entered into the command window

Boucheta.A Page 7
3.1 Find and execute MATLAB programs written in '.m' files and
sorted in a folder

When organizing the files containing the matlab programs into a folder created in
this purpose, for example "C:\programmatlab", you need to provide Matlab with the information to
that he can find the folder in question; this is done by defining the access path
(command File/Set Path)

Order
allowing to
define the
access path
again
file

Boucheta.A Page 8
Selection of
file

Once you've clicked 'save', Matlab will look for the necessary files contained in the
matlab file
Boucheta.A Page 9
Implementation and modification of a program

To modify the program, launch the Matlab editor.

>>edit

a new window opens where we write the program text (see for example
example matlab.m

( In a program saved in a file, an instruction will end with a period-


comma in order to avoid displaying the result of the instruction in the command window.)

and we save it in the form of a file 'file.m'; the '.m' extension indicates that
It is a program executable by Matlab (don't forget to save it again)
when modifying the file
in the command line of matlab, we choose the 'current directory' where we save the
file (you can choose a folder other than the 'current directory')

to run it in the matlab window

>>examplematlab

at the end of the execution of matlab we find in this window the '>>'
A comment starts with a % sign (at the beginning of a line or after an instruction)
Here is a program trial1.m

Which generates (function rand) a pseudo-random sequence "a" whose length is that
from the sequence "t" (here 1024) and which traces it

Its execution in the command window

Boucheta.A Page 10
produces the display

It is useful to juggle the display windows of the charts well; here are a few
current operations (additional possibilities will be described in a paragraph
further; once the basics are acquired, one will need to refer to the Matlab documentation to
to use the numerous possibilities offered)

If we want to overlay a second graph on a graph we've just plotted, we use


the orderhold on

Here are two programs plotting a sine and a cosine

Boucheta.A Page 11
If we run the first program, then the command "holdand the second program

The two plots are thus superimposed.

(practice by applying commands of the typehold, hold onandholdoff)

Boucheta.A Page 12
Tip: If you plan to write complicated programs, start with one case.
simple that you will gradually enrich by carefully checking before a new one
Modification so that your program works correctly.

5 Operations in matlab

It often happens that we apply the same operation to all the elements of an array. We can
doing it by performing a loopfor» ... «endon the operation

(Here we see an example of a loop and index manipulation);

One can also write not only in a condensed manner (and sometimes harder to read) but
also optimized to speed up calculations the 'point' code before the product code
(.* instead of *)
and thus we will apply the same product on all pairs of elements having the same position
(the same index) in both sequences

who will give the same result

Boucheta.A Page 13
6 Management of charts

We saw an example of a simple plot; here is another one where we provide the abscissa and
the ordinate for two graphs

x = [0:0.01:2*pi];
>> plot(x, cos(x), x, sin(x))

clear all
close all % close the old figures
figure(1); % to create a new figure window
x = [0:0.01:2*pi];
plot(x, cos(x), '.', x, sin(x), '+') % cos(x) as points, sin(x) as +

Boucheta.A Page 14
To add a title and a caption

sine and cosine


legend('cos(x)','sin(x)',0) % the '0' places the legend next to the curves

It is common to want to display multiple figures on the same screen, which is done with the
subplot function

Boucheta.A Page 15
Examples of commands explained in the MATLAB manual

stem grid
xlabel ylabel
title bar
figure step
disp input

Boucheta.A Page 16
TP N 2 bisection method

First method

symsx
d=input('enter f(x)= ');
f=inline(d);
a=
b=input('b=\n');
n=input('n= ');
foru=1:n
x=(a+b)/2
c=f(x);
h=abs(c);
ifh <= n
break
end
iff(a)*c<0
b=x
continue
else
a=x;
continue
end
end

second method

myfunction = @(x)x.^2 - 6;
a=0;
b=5;
xm=(a+b)/2;
while abs(myfunction(xm)) > 0.01
if(myfunction(xm)*myfunction(b)<0)
a=xm;
else
b=xm;
end
xm=(a+b)/2;
end
fprintf ('the root is %g\n', xm)

3rd method

close all
clc
f=@(x)(x^3-x^2-x-1);
enter the first approximation xl:
xu=input('enter the second approximation xu:');
acc=input('enter the value of accuracy:');
while((f(xl)*f(xu))>0)
enter the first approximation xl:
enter the second approximation xu:
end
while(abs(xu-xl)>acc)
xm = (xl + xu) / 2;
if(f(xl)*f(xm)<0)
xu=xm
end
xl=xm;
end
fprintf('the root is=%f',xm);

To numerical method Boucheta.A


TP N 3 Fixed Point Method
1. Principle
To solve the equation F(x) = 0, the iteration method, also called the fixed point method, proceeds
as follows:
a) Choose a starting value x1
b) Iterate as many times as needed: xn+1 = g(xn) for n = 1, 2, ....
This method is therefore, in principle, simpler to implement than the previous methods.
Moreover, it requires fewer operations per iteration.
The tricky part here is to make a 'suitable choice' of the iteration function g(x).
Indeed, we can express the equation to solve F(x) = 0 in the equivalent form x = g(x) of an infinite number.
in ways
2. Exercise
Let the function f  x 3x 0.2exwrite a script (program) Matlab to find the root of
this equation over the interval 0.1 by the fixed point method, using the following algorithm:

General program
clearall; closeall; clc;
symsx
d=input('enter g(x) = ')
g=inline (d);
x0 = input('x0 approximate value = ' ');
eps = ');
m=input('m repetition = ');
x=x0
fori=0:m
y=x
x=g(x)
h=abs(y);
ifh <= eps
end
disp([y x (x-y)]);
end
fprintf ('the root is %g\n', x);

Numerical Method Boucheta.A


TP N 4 Newton-Raphson Method 1

Principle and algorithm of the iteration method


The Newton method is an iterative algorithm used to calculate a root.
of a function whose derivative is known. Starting from an initial value x0, the method
Newton's iteration x_{n+1} = x_n - f(x_n) / f'(x_n).
In taking by example the function f(x) = cos(x) - x^3, to write a
newton_function(f, df, x0, n) which takes a function f, its derivative f′, a value of
departure and a maximum number of iterations that returns the approximation of the
root at the end of iterations.
Algorithm

the Newton method, in general


symsx
fun=input('enter fun = ');
f=inline (fun);
z = diff(f(x));
f1=inline (z);
x0=input('x0 = ');
x=x0
for i=0:30
y = x
x = y - [f(x) / f1(x)];
if x == y
break
end
end
Example
% %************* % Study of the function : * % f(x)=exp(x)-[Link](x) *
% % ************************* NEWTON's Method ***************
x=-1:0.1:1.7;
f=exp(x)-2*cos(x);
figure(1);
plot(x,f); grid on;
Function: f(x)=exp(x)-[Link](x)
clearall;

x(1)=input('Give the initial value x(1): \n');


e=1e-10;
n=5000;
for i=2:n
f=exp(x(i-1))-2*cos(x(i-1));
diff=exp(x(i-1))+2*sin(x(i-1));
x(i)=x(i-1)-f/diff;
if abs(x(i) - x(i-1)) <= e
xp=x(i);
fprintf('xp=%f\n',x(i));
break;
end
end
j=1:i;
figure(2);
plot(j,x(j),'*r',j,x(j));
Number of iterations
Convergence of the solution: Newton-Raphson method.
The successive values of x(i) are:
x'

Numerical Method Lab Boucheta.A


TP N 4 Newton-Raphson Method 2

x0 = 0.5
def f(x):
return [Link](x) - x**3

def df(x):
return -[Link](x) - 3 * x**2

def newton(f, df, xi, n):


if(n == 0):
return xi
else:
return newton(f, df, xi - f(xi)/df(xi), n-1)

print(newton(f, df, x0, 5))

Numerical Method Lab Boucheta.A


TP N 5 Newton's Interpolation

Principle of the method

The (general) problem of interpolation consists of determining a curve that passes through
by given points in the plane and derived from, for example, experimental measurements. the
The sought curve is the graph of a function and more precisely of a polynomial. As
We will see it, the degree of this polynomial is determined by the number of points.
 n 1
Let's give ourselves  distinct pairs of points x,x,.......,x
0 1 and  n 1  real values
y0,y1,y2,...........,yn We are looking for a polynomial such that its graph passes through the

points  xi,yi  pouring 0,.....,n. More precisely, the interpolation problem


a polynomial consists of finding a polynomial of degree at most equal to n , which takes the value
yI to the point x i .

We call Newton's base relative to x0,x1,.......,xn ,the base formed by the n 1


polynomials1  x x0  ,  x x0x x1  ,.......,  x x0x x1  ........ x xn1 
The polynomial p Pn can write in the form of
i
1 y0
p x a0 a1  x x0   a2  x x0x x1   ......  an x  eleven  wateri
i 0 hii

Example

Starting from the data in the table below, form the polynomial using the method of
NEWTON.
Xi 1 2 3 4 5 6 7
YI 3 7 13 21 31 43 57

Interpolation program in MATLAB


The program calculates the NEWTON polynomial
clear all; close all; clear the console;
x = [1,2,3,4,5,6,7 ]';
y = [ 3, 7, 13, 21, 31, 43, 57]';
p = y;
fori = 1:(length(x) - 1)
p( (i + 1):end ) = (p( (i + 1):end ) - p( i:(end - 1) )) ./...
(x((i + 1):end) - x(1:(end - i)));
end
p
figure;plot(x,y,'kv-');xlabel('x'); ylabel('y');grid;
title('Figure: function fx')
axis([0 8 0 58]);

TP Numerical Method Boucheta.A


TP N 6 Chebyshev Approximation
Principle of the method
Interpolation of Pafnouti Chebyshev imposes a choice of nodes (see, Eqs. (02) or (03)) in
the interval, acalled
, b Chebyshev points. This is therefore a Lagrange interpolation carried out in
specific points. Taking into account this particular distribution of nodes, it can be shown that, if
f  x is differentiable on converge n x
, so Pwhen
a , b towards for all x f  x a Thus,
The Chebyshev nodes are determined by minimizing the quantity:

maxx a,b
 x xI  ......................(01)
i 0

Indeed, equation (01) is minimal for the nodes that cancel the Chebyshev polynomials,
let it be:

ba

b a  2 n i   1   02
xi cos with i 0,1,.......,n
2 2 2n
There is also another non-uniform distribution of interpolation nodes, having the same
convergence characteristics of the Chebyshev nodes, defined by the Chebyshev nodes
Gauss, let it be:

b a

b a
cos
 2i 1   03
xi with i 0,1,.......,n
2 2  n 1  2
Example
1
Let the function f  x , with x  5.5 We will consider the interpolation nodes
1 x 2
following :
x0 5 ,x1  4 ,x 2 3 ,x3 2 ,x4  1 ,x 5 0,x6 1,x7 2 ,x 8 3,x9 4,x10 5.
Interpolation program in MATLAB
Implementation, under MATLAB, of the Chebyshev method
clearall, closeall, clc;
format long
n=11;%POLYNOMIAL OF DEGREE n-1
x(1)=-5 ; x(2)=-4; x(3)=-3;x(4)=-2 ; x(5)=-1; x(6)=0;
x(7)=1; x(8)=2; x(9)=3;x(10)=4; x(11)=5;
y=1./(1+x.^2);
interv = 1000; dx = (x(11) - x(1)) / interv;
xvar = x(1):dx:x(11); polyn = 0;
x=(x(11)+x(1))/2+((x(11)-x(1))/2)*cos((2*(n-(1:n))+1)*pi/(2*n));
xChe = x; %? THE NODES xi CANCELLING THE POLYNOMIALS OF TCHEBYCHEV:
THIS IN ORDER TO MINIMIZE THE GAP BETWEEN Pn(x) AND THE FUNCTION f(x) AT
% INTERPOLATE
for i=1:n
lag=1;
for j=1:n
if(i!=j)
lag=(xvar-xChe(j))./(xChe(i)-xChe(j)).*lag;
end
end
figure(1);plot(xChe(i),y(i),'+k','MarkerSize',12,'LineWidth',1);
hold on;
polyn = polyn + lag * y(i);

end
hold on
figure;plot(xvar,1./(1+xvar.^2),'r',xChe(i),y(i),'+k',xvar,polyn,'b');xlabel('X');
y
Figure: Attenuation of the Runge phenomenon at the Chebyshev nodes

TP Numerical Method Boucheta.A


TP N 7 Numeric Integrations
Example
4
Calculation ofI e x dx by the integration methods the values of the function exat the point
0

sont données (0 ,1) ; (1 ,2.7183) ; (2 ,7.3891) ; (3 ,20.0855) ; (4 ,54.5982)

xi 0 1 2 3 4

yi 1 2.7183 7.3891 20.0855 54.5982

1-Write a program that calculates this integral using the Trapezoidal method.

4 1
x
The Trapezoid Formula: I e x dx  y0y 2 4  y1  y y2 3 
0
2 i 1

With the given integration step h x We find:


4
1
I e x dx  1 54.5982 2  2.7183
 7.3891 20.0855 
57.992
0
2
2-Same question for Simpson's method
4
x
The Simpson's formula: I x
dx  y0y 4 4 3y y 2 1
y 2
0
3

With the given integration step h x 1we find:


4
1
I e x dx  1 54.5982 4  2.7183
 20.0855 2 7.3891
 53.8639
0
3

Program integration in MATLAB


program by Trapezes
format long
% Programmed trapezoidal method
f=inline('exp(x)');
a=0;
b=4;
n=4;
h=(b-a)/n;
x=[a:h:b];
y=f(x);
sigma = sum(y(2:n));
It=(h/2)*(y(1)+y(n+1)+2*sigma)
Utilization of the predefined Matlab function: TRAPZ
Itm=trapz(y)
The exact value
IEx=(exp(4) -exp(0))
% % % % % % % % % % % %

TP Numerical Method Abderrahmane Boucheta


% % % % % % % % % % % %
% % % % % % % % % % % %

program by Simpson's method


f=inline('exp(x)');
a=0;
b=4;
n=4;
h = (b - a) / n;
x = [a:h:b];
y = f(x);
0
k=n/2;
for i=1:k
sigma1 = sigma1 + y(2 * i - 1);
end
sigma2=0;
for i=1:k
sigma2 = sigma2 + y(2 * i);
end
Is = (h/3) * (y(1) + y(n+1) + 2 * sigma1 + 4 * sigma2)
% Utilization of the predefined Matlab function: QUAD
Ism=quad(f,0,4)

TP Numerical Method Abderrahmane Boucheta

You might also like