Lab1 - Basics of Matlab
Lab1 - Basics of Matlab
Probability theory
and mathematical
statistics
INTRODUCTION TO MATLAB
Variables in Matlab
Valid Names - A valid variable name starts with a letter, followed by letters, digits, or underscores.
MATLAB® is case sensitive, so A and a are not the same variable. The maximum length of a variable
name is the value that the namelengthmax command returns. You cannot define variables with the
same names as MATLAB keywords, such as if or end. For a complete list, run the iskeyword command.
Create Variables - To create a new variable, enter the variable name in the Command Window, followed
by an equal sign (=) and the value you want to assign to the variable. For example, if you run these
statements, MATLAB adds the three variables x, A, and I to the workspace:
x = 8.16;
A = [1 2 3; 4 5 6; 7 8 9];
I = x*A;
You do not have to declare variables before assigning values to them. If you do not end the assignment
statement with a semicolon (;), MATLAB displays the result in the Command Window.
Scalar arithmetic
operations
Symbol Operation Matlab form
^^ Exponentiation: a^b
a^b
** Multiplication: a*b
a*b
// Right division: a/b
a/b
\ Left division: a\b
\ a\b
+ Addition: a+b
+- Subtraction: a+b
a-b
- a-b
An Example Session
8/10
ans =
0.8000
r=8/10
r=
0.8000
r
r=
0.8000
s=20*r
s=
16
Order of precedence
Precedence Operation
First Parentheses, evaluated starting with the innermost pair.
Second Exponentiation, evaluated from left to right.
Third Multiplication and division with equal precedence, evaluated from left to right.
Fourth Addition and subtraction with equal precedence, evaluated from left to right.
Examples of Precedence
• 8 + 3*5 • 3*4^2 + 5
• ans = • ans =
• 23 • 53
• 8 + (3*5) • (3*4)^2 + 5
• ans = • ans =
• 23 • 149
• (8 + 3)*5 • 27^(1/3) + 32^(0.2)
• ans = • ans =
• 55 • 5
• 4^2128/4*2 • 27^(1/3) + 32^0.2
• ans = • ans =
• 0 • 5
Commands for managing
the work session
Command Description
clc Clears the Command window
clear Removes all variables from memory
clear var1 var2 Removes variables var1 and var2 from memory
exist(’name’) Determines is a file or variable exists having the name ’name’
Complex Number
Operations
The number c1 = 1 – 2i is entered as follows: c1 = 1-
2i or c1 = 1-2*1i
• An asterisk is not needed between i or j and a number, although it is required with a
variable, such as
c2 = 5*1i*c1
• Be careful. The expressions
y = 7/2*i
and
x = 7/2i
give two different results:
y = (7/2)i = 3.5i
and
x = 7/(2i) = –3.5i
Numeric display formats
Command Description
format SHORT Scaled fixed point format with 5 digits.
format LONG Scaled fixed point format with 15 digits for double and 7 digits for single.
format SHORTE Floating point format with 5 digits
format LONGE Floating point format with 15 digits for double and 7 digits for single.
format SHORTG Best of fixed or floating point format with 5 digits.
format LONGG Best of fixed or floating point format with 15 digits for double and 7 digits for single.
Arrays
The
numbers 0, 0.1, 0.2, …, 10 can be assigned to the variable u by typing
u = 0:0.1:10.
To compute for , the session is:
u = 0:0.1:10;
w = 5*sin(u);
The single line, w = 5*sin(u), computed the formula 101 times.
Array Index
u(7)
ans =
0.6000
w(7)
ans =
2.8232
Use the length function to determine how many values are in an array.
m = length(w)
m=
101
Some commonly used
mathematical functions
Function Matlab syntax
exp(x)
exp(x)
sqrt(x)
sqrt(x)
log(x)
log(x)
log10(x)
log10(x)
cos(x)
cos(x)
sin(x)
sin(x)
tan(x)
tan(x)
acos(x)
acos(x)
asin(x)
asin(x)
atan(x)
Important! The Matlab trigonometricatan(x)
functions use radian measure.
Important! The Matlab trigonometric functions use radian measure.
Some Built-in functions
Function Description
mean(A) Average or mean value of A
max(A), min (A) If A is a vector, then min(A) returns the smallest element of A.
If A is a matrix, then min(A) is a row vector containing the minimum value of
each column. max(A) works similarly, but with the maximum of A.
sum(A) Summation of the elements of A
sort(A) Sort in ascending or descending order.
median(A) For vectors, median(a) is the median value of the elements in x. For matrices,
median(A) is a row vector containing the median value of each column.
std(A) Standard deviation
det(A) Determinant of a square matrix
inv(A) Inverse of the square matrix A
size(A) D=size(A), for M-by-N matrix A, returns the two-element row vector
D=[M,N] containing the number of rows and columns in the matrix.
length(A) Returns the length of vector A. It is equivalent to MAX(SIZE(A)) for non-
empty arrays and 0 for empty ones.
flip(A) Flip the order of elements
prod(A) P=prod(A)is the product of the elements of the vector A. If A is a matrix, P is
a row vector with the product over each column.
Important! If A is a matrix, then some of these functions work differently, please check the helper.
Operators (relational, logical)
Operator Description
== Equal to
~= Not equal to
< Strictly smaller
> Strictly greater
<= Smaller than or equal to
>= Greater than or equal to
& And operator
| Or operator
Vectors
(One dimensional arrays)
To create a row vector, separate the elements by commas or spaces. Use square
brackets:
p = [3,7,9]
p =
3 7 9
You can create a column vector by using You can also create a column vector by
the transpose notation ('). separating the elements by semicolons.
For example,
p = [3,7,9]'
g = [3;7;9]
p =
g =
3
3
7
7
9
9
You can create row vectors by
''appending'' one vector to another.
For example, to create the row vector u whose first three columns
contain the values of
r = [2,4,20]
and whose fourth, fifth, and sixth columns contain the values of
w = [9,-6,3]
you type
u = [r,w]
The result is the vector
u = [2,4,20,9,-6,3]
You can create column vectors by
''appending'' one vector to another.
For example, to create the column vector u whose first three rows
contain the values of
r = [2;4;20]
and whose fourth, fifth, and sixth rows contain the values of
w = [9;-6;3]
you type
u = [r;w]
The result is the vector
u = [2;4;20;9;-6;3]
The colon operator (:)
The colon operator (:) easily generates a large vector of regularly spaced elements.
Typing
x = m:q:n
or
x = (m:q:n)
creates a vector x of values with a spacing q. The first value is m. The last value is n if m-n
is an integer multiple of q. If not, the last value is less than n.
For example, typing x = 0:2:8 creates the vector x = [0,2,4,6,8], whereas
typing x = 0:2:7 creates the vector x = [0,2,4,6].
To create a row vector z consisting of the values from 5 to 8 in steps of 0.1, type
z = 5:0.1:8
If the increment q is omitted, it is presumed to be 1. Thus typing y = -3:2 produces the
vector y = [-3,-2,-1,0,1,2].
Creating vectors with the
linspace command
The linspace command also creates a linearly spaced row vector, but instead you
specify the number of values rather than the increment.
The syntax is linspace(x1,x2,n), where x1 and x2 are the lower and upper limits
and n is the number of points.
A = [2,4,10;16,3,7];
c = [a b];
c =
1 3 5 7 9 11
D = [a;b]
D =
1 3 5
7 9 11
Array Addressing
The colon operator selects individual elements, rows, columns, or ''subarrays'' of
arrays. Here are some
examples:
• v(:) represents all the row or column elements of the vector v.
• v(2:5) represents the second through fifth elements; that is v(2), v(3), v(4), v(5).
• A(:,3) denotes all the elements in the third column of the matrix A.
• A(:,2:5) denotes all the elements in the second through fifth columns of A.
• A(2:3,1:3) denotes all the elements in the second and third rows that are also in the
first through third columns.
• v = A(:) creates a vector v consisting of all the columns of A stacked from first to last.
• A(end,:) denotes the last row in A, and A(:,end) denotes the last column.
Arrays
You
can use array indices to extract a smaller array from another array. For
example, if you first create the array B
54 -16 78 20
-120 42 54 122
Element-by-element
operations
Symbol Operation Form Examples
+ Scalar-array addition A+b [6,3]+2=[8,5]
- Scalar-array subtraction A-b [8,3]-5=[3,-2]
+ Array addition A+B [6,5]+[4,8]=[10,13]
- Array subtraction A-B [6,5]-[4,8]=[2,-3]
.* Array multiplication A.*B [3,5].*[4,8]=[12,40]
./ Array right division A./B [2,5]./[4,8]=[2/4,5/8]
.\ Array left division A.\B [2,5].\[4,8]=[2\4,5\8]
2.^[3,5]=[2^3,2^5]
.^ Array exponentiation A.^B [3,5].^[2,4]=[3^2,5^4]
Matrix-Matrix Multiplication
In
the product of two matrices AB, the number of columns in A must equal the number of rows in
B. The product AB has the same number of rows as A and the same number of columns as B.
For example,
A = [6,-2;10,3;4,7];
B = [9,8;-5,12];
A*B
ans =
64 24
75 116
1 116
A graphics window showing
a plot
plot command in MATLAB
plot(X,Y) creates a 2-D line plot of the data in Y versus the corresponding values in X.
Example:
X=[1,2,3,4,5]
X=
1 2 3 4 5
Y=[1,4,9,16,25]
Y=
1 4 9 16 25
plot(X,Y)
plot command in MATLAB
To plot the 5 point defined by X and Y, you can use for example the * marker.
Example:
X=[1,2,3,4,5]
X=
1 2 3 4 5
Y=[1,4,9,16,25]
Y=
1 4 9 16 25
plot(X,Y, '*')
plot line style, marker and
colour
Line Style Description Marker Description
- Solid line (default) o Circle
-- Dashed line + Plus sign
: Dotted line * Asterisk
-. Dash-dot line . Point
Colour Description x Cross
y yellow s Square
m magenta d Diamond
c cyan ^ Upward-pointing triangle
r red v Downward-pointing triangle
g green > Right-pointing triangle
b blue < Left-pointing triangle
w white p Pentagram
k black h Hexagram
Plotting Polynomials
The function polyval(a,x)evaluates a polynomial at specified values of its
independent variable x, which can be a matrix or a vector. The polynomial’s
coefficients of descending powers are stored in the array a. The result is the same size
as x.
a = [9,-5,3,7];
x = -2:0.01:5;
f = polyval(a,x);
plot(x,f),xlabel('x'),ylabel('f(x)')
Plotting and labelling
The
following MATLAB session plots for , where y represents the height of a rocket after
launch, in miles, and x is the horizontal (downrange) distance in miles.
x = 0:0.1:52;
y = 0.4*sqrt(1.8*x);
plot(x,y)
xlabel('Distance (miles)')
ylabel('Height (miles)')
title('Rocket Height as a Function of Downrange Distance')
Multiple Graphs
First method:
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2)
grid on
Then the editor window appears, where you can edit your script:
My first scripts
In the ”Editor” window you can write your script and save it on the local computer. (When
saving the script do not forget about the naming regulations!)
Example for a simple script:
x=-5:0.01:5;
y=x.^2;
plot(x,y)
xlabel('Horizontal axis')
ylabel('Vertical axis')
title('The result of my first script is a Parabola')
After typing in the code you can run it, by clicking the ”Run” icon on the ”Editor” tab:
If the script wasn’t saved previously, Matlab asks you to save the script in an m file.
Let’s name the script parabola.
My first scripts
If you save it in a folder which is in the ”Path list”, then you can run the script by typing
parabola in the ”Command Window”.
If the folder is not in the ”Path list”, you can add your folder, by clicking the ”Set Path” icon
on the ”Home” tab.
Keep in mind when using
script files
1. The name of a script file must begin with a letter, and may include digits and
the underscore character, up to 63 characters.
2. Do not give a script file the same name as a variable.
3. Do not give a script file the same name as a MATLAB command or function.
You can check to see if a command, function or file name already exists by
using the exist command.
COMMENTS
The comment symbol may be put anywhere in the line. MATLAB ignores
everything to the right of the % symbol. For example,
% This is a comment.
x = 2+3 % So is this.
x=
5
Note that the portion of the line before the % sign is executed to compute x.
Flow Control
if
for
while
break
…
Control Structures
If Statement Syntax Some Examples
if ((a>3) & (b==5))
disp('Some MATLAB Commands');
if (Condition_1)
end
MATLAB Commands if (a<3)
elseif (Condition_2) disp('Some MATLAB Commands');
elseif (b==5)
MATLAB Commands disp('Some other MATLAB Commands');
end
elseif (Condition_3)
if (a<3)
MATLAB Commands disp('Some MATLAB Commands');
else
else
disp('Some other MATLAB Commands');
MATLAB Commands end
end
Control Structures
Some Examples
s=0;
For loop syntax for i=1:100
s=s+i;
end
for i=Index_Array s
while (condition)
MATLAB Commands
end
Example
a=10;
b=5;
while ((a>3) & (b==5))
disp('a is greater then 3 and b is equal to 5.');
a=a-1;
end