Introduction To Matlab
Introduction To Matlab
2
Commands
>>help
>>clc
>>clear
>>clear all
>>save
>>load
3
Matrix
[1,1 1,2 . 1,n
>> x=[1 2 3]
2,1 2,2 . 2,n x =
1 2 3
3,1 3,2 . 3,n
. . . >> x=[1,2,3]
x =
m,1 m,2 . m,n] 1 2 3
>> x=[1
>> N = 5:10:35 2
3
N = 4];
5 15 25 35 >> x=[1;2;3;4]
>> P = [1:3; 30:-10:10] x =
P = 1
2
1 2 3 3
30 20 10 4
4
Matrix
>> A = [1:3;4:6;7:9]
>> a=[1 2]; A = x = zeros(1,3)
>> b=[3 1 2 3 x =
4]; 4 5 6 0 0 0
7 8 9
>> a*b
x = ones(1,3)
ans = >> mean(A) x =
11 ans = 1 1 1
4 5 6
>> b*a
x = rand(1,3)
ans = >> sum(A) x =
3 6 ans = 0.9501 0.2311 0.6068
4 8 12 15 18
5
Matrix
6
Linear equation system
X =inv(A)*B
A = [1 2 3; 5 1 4; 3 2 1] B = [-5; -1; 5 ] X=
A= B=
1 2 3 -5 2
5 1 4 -1 1
3 2 1 5 -3
7
Polynomial: roots
❖Find the roots of the polynomial
8
Polynomial: poly
❖It is known that the roots of a polynomial are -1, -2, -3,
4+5j and 4-5j. Compute the coefficients of this polynomial.
9
Polynomial: polyval
❖Evaluate the polynomial at x=-3
10
Polynomial: conv
11
Polynomial: polyder
12
Polynomial
dathuc=poly([1 2 3]);
x=0:0.01:4;
y=polyval(dathuc,x);
plot(x,y)
grid on
nghiem=roots(dathuc)
13
Script file
❖MATLAB recognizes two types of files: script files and
function files. Both types are referred to as m−files since
both require the .m extension.
❖A script file consists of two or more functions.
14
Function file
binhphuong.m
function y=binhphuong(x)
y=x^2
end
15
Visualization
x = 0:pi/100:2*pi; x = 0:pi/100:2*pi;
y = sin(x); y = sin(x);
plot(x,y) stem(x,y)
1 1
0.8 0.8
0.6 0.6
0.4 0.4
0.2 0.2
0 0
-0.2 -0.2
-0.4 -0.4
-0.6 -0.6
-0.8 -0.8
-1 -1
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
16
Visualization 1
0.8
x = 0:pi/100:2*pi;
0.6
0.4
0.2
y1 = sin(x); 0
-0.2
y2=cos(x); -0.4
-0.6
plot(x,y1,x,y2) -0.8
-1
0 1 2 3 4 5 6 7
x = 0:pi/100:2*pi; 1
0.5
subplot(2,2,1) 0
-0.5
-1
plot(x,sin(x))
0 2 4 6 8
0.5
subplot(2,2,4) 0
-0.5
plot(x,cos(x)) -1
0 2 4 6 8
17
Visualization
x=0:0.1:10*pi;
stem(x,sin(x).*exp(-0.1*x))
18
Visualization
t=0:pi/100:2*pi; t=0:pi/100:2*pi;
x=cos(t); plot(exp(i*t))
y=sin(t); axis('square')
plot(x,y)
axis('square')
19
mesh
colormap jet
t=0:pi/100:2*pi;
[X Y Z]=cylinder(t);
mesh(X,Y,Z)
20
mesh
colormap jet
t=-2*pi:pi/100:2*pi;
[X Y Z]=cylinder(t);
mesh(X,Y,Z)
21
mesh
colormap jet
t=0:pi/100:2*pi;
[X Y Z]=cylinder(2+cos(t));
mesh(X,Y,Z)
22
mesh
colormap jet
x=-50:50;
y=-50:50;
for a=1:101
for b=1:101
z(a,b)=sqrt(x(a)^2+y(b)^2);
end
end
meshc(x,y,z) 23