MATLAB Basics: Numerical Methods Guide
MATLAB Basics: Numerical Methods Guide
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
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.
Boucheta.A Page 2
2 First operations: Keyboard commands (to perform simple calculations, a
graph displays, ...) in the command window
Entry to
keyboard
The result
displays
Entry to
keyboard
The result is
calculated and displayed
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'
Boucheta.A Page 3
Display in the
new window of
values of the elements of
the sequence b
b = a + 2;
and no
b = a + 2
If we want to enter a long sequence of regular intervals without entering all the values, we
use the colon ':'
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.
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
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
>>edit
a new window opens where we write the program text (see for example
example matlab.m
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')
>>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
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)
Boucheta.A Page 11
If we run the first program, then the command "holdand the second program
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
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
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
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);
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);
x0 = 0.5
def f(x):
return [Link](x) - x**3
def df(x):
return -[Link](x) - 3 * x**2
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
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
maxx a,b
x xI ......................(01)
i 0
Indeed, equation (01) is minimal for the nodes that cancel the Chebyshev polynomials,
let it be:
ba
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
xi 0 1 2 3 4
1-Write a program that calculates this integral using the Trapezoidal method.
4 1
x
The Trapezoid Formula: I e x dx y0y 2 4 y1 y y2 3
0
2 i 1