MATLAB Course - Part 1
MATLAB Course - Part 1
In MATLAB we type vectors and matrices like this:
[
]
>> A = [1 2; 3 4]
A = 1 2
3 4
or:
>> A = [1, 2; 3, 4]
A = 1 2
3 4
To separate rows, we use a semicolon ;
To separate columns, we use a comma , or a space .
To get a specific part of a matrix, we can type like this:
>> A(2,1)
ans =
3
or:
>> A(:,1)
ans =
1
3
or:
16 MATLAB Basics
MATLAB Course - Part I: Introduction MATLAB Basics
>> A(2,:)
ans =
3 4
From 2 vectors x and y we can create a matrix like this:
>> x = [1; 2; 3];
>> y = [4; 5; 6];
>> B = [x y]
B = 1 4
2 5
3 6
4.2.1 Colon Notation
The colon notation is very useful for creating vectors:
Example:
This example shows how to use the colon notation creating a vector and do some calculations.
[End of Example]
17 MATLAB Basics
MATLAB Course - Part I: Introduction MATLAB Basics
Task 3: Vectors and Matrices
Type the following vector in the Command window:
[
]
Type the following matrix in the Command window:
[
]
Type the following matrix in the Command window:
[
]
Use Use MATLAB to find the value in the second row and the third column of matrix .
Use MATLAB to find the second row of matrix .
Use MATLAB to find the third column of matrix .
[End of Task]
Deleting Rows and Columns:
You can delete rows and columns from a matrix using just a pair of square brackets [].
Example:
Given:
[
]
To delete the second column of a matrix , use:
>>A=[0 1; -2 -3];
>>A(:,2) = []
A =
0
-2
[End of Example]
18 MATLAB Basics
MATLAB Course - Part I: Introduction MATLAB Basics
4.3 Tips and Tricks
Naming conversions:
When creating variables and constants, make sure you create a name that is not already exists in
MATLAB. Note also that MATLAB is case sensitive! The variables x and X are not the same.
Use the which command to check if the name already exists: which all <your name>
Example:
>> which -all sin
built-in (C:\Matlab\R2007a\toolbox\matlab\elfun\@double\sin) % double
method
built-in (C:\Matlab\R2007a\toolbox\matlab\elfun\@single\sin) % single
method
Large or small numbers:
If you need to write large or small numbers, like
] [
]
Then
[
]
The elements of A.*B are the products of the corresponding elements of A and B.
We have the following array operators:
20 MATLAB Basics
MATLAB Course - Part I: Introduction MATLAB Basics
Example:
>> A = [1; 2; 3]
A =
1
2
3
>> B = [-6; 7; 10]
B =
-6
7
10
>> A*B
??? Error using ==> mtimes
Inner matrix dimensions must agree.
>> A.*B
ans =
-6
14
30
[End of Example]
21
5 Linear Algebra; Vectors and
Matrices
Linear Algebra is a branch of mathematics concerned with the study of matrices, vectors, vector
spaces (also called linear spaces), linear maps (also called linear transformations), and systems of
linear equations.
MATLAB are well suited for Linear Algebra. This chapter assumes you have some basic understanding
of Linear Algebra and matrices and vectors.
Here are some useful functions for Linear Algebra in MATLAB:
Function Description Example
rank
Find the rank of a matrix. Provides an estimate of the number of
linearly independent rows or columns of a matrix A.
>>A=[1 2; 3 4]
>>rank(A)
det
Find the determinant of a square matrix
>>A=[1 2; 3 4]
>>det(A)
inv
Find the inverse of a square matrix
>>A=[1 2; 3 4]
>>inv(A)
eig
Find the eigenvalues of a square matrix
>>A=[1 2; 3 4]
>>eig(A)
ones
Creates an array or matrix with only ones
>>ones(2)
>>ones(2,1)
eye
Creates an identity matrix
>>eye(2)
diag
Find the diagonal elements in a matrix
>>A=[1 2; 3 4]
>>diag(A)
Type help matfun (Matrix functions - numerical linear algebra) in the Command Window for more
information, or type help elmat (Elementary matrices and matrix manipulation).
You may also type help <functionname> for help about a specific function.
Before you start, you should use the Help system in MATLAB to read more about these functions.
Type help <functionname> in the Command window.
5.1 Vectors
Given a vector :
[
Example:
22 Linear Algebra; Vectors and Matrices
MATLAB Course - Part I: Introduction MATLAB Basics
[
]
>> x=[1; 2; 3]
x =
1
2
3
The Transpose of vector x:
>> x'
ans =
1 2 3
The Length of vector x:
Orthogonality:
[End of Example]
5.2 Matrices
Given a matrix :
[
Example:
[
]
>> A=[0 1;-2 -3]
A =
0 1
-2 -3
[End of Example]
23 Linear Algebra; Vectors and Matrices
MATLAB Course - Part I: Introduction MATLAB Basics
5.2.1 Transpose
The Transpose of matrix :
Example:
[
]
[
]
>> A'
ans =
0 -2
1 -3
[End of Example]
5.2.2 Diagonal
The Diagonal elements of matrix A is the vector
[
]
Example:
>> diag(A)
ans =
0
-3
[End of Example]
The Diagonal matrix is given by:
[
Given the Identity matrix I:
24 Linear Algebra; Vectors and Matrices
MATLAB Course - Part I: Introduction MATLAB Basics
[
]
Example:
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
[End of Example]
5.2.3 Triangular
Lower Triangular matrix L:
[
]
Upper Triangular matrix U:
[
]
5.2.4 Matrix Multiplication
Given the matrices
and
, then
where
Example:
>> A = [0 1;-2 -3]
A =
0 1
-2 -3
>> B = [1 0;3 -2]
B =
1 0
25 Linear Algebra; Vectors and Matrices
MATLAB Course - Part I: Introduction MATLAB Basics
3 -2
>> A*B
ans =
3 -2
-11 6
Check the answer by manually calculating using pen & paper.
[End of Example]
Note!
Note!
5.2.5 Matrix Addition
Given the matrices
and
, then
Example:
>> A = [0 1;-2 -3]
>> B = [1 0;3 -2]
>> A + B
ans =
1 1
1 -5
Check the answer by manually calculating using pen & paper.
[End of Example]
5.2.6 Determinant
26 Linear Algebra; Vectors and Matrices
MATLAB Course - Part I: Introduction MATLAB Basics
Given a matrix
Then
||
Example:
A =
0 1
-2 -3
>> det(A)
ans =
2
Check the answer by manually calculating using pen & paper.
[End of Example]
Notice that
and
Example:
>> det(A*B)
ans =
-4
>> det(A)*det(B)
ans =
-4
>> det(A')
ans =
2
>> det(A)
27 Linear Algebra; Vectors and Matrices
MATLAB Course - Part I: Introduction MATLAB Basics
ans =
2
[End of Example]
5.2.7 Inverse Matrices
The inverse of a quadratic matrix
is defined by:
if
For a matrix we have:
[
The inverse
is then given by
Example:
A =
0 1
-2 -3
>> inv(A)
ans =
-1.5000 -0.5000
1.0000 0
Check the answer by manually calculating using pen & paper.
Notice that:
[End of Example]
5.3 Eigenvalues
Given
where eig = Eigenvalues, diag = Diagonal, det = Determinant
Use MATLAB to prove the following:
where is the unit matrix
29 Linear Algebra; Vectors and Matrices
MATLAB Course - Part I: Introduction MATLAB Basics
[End of Task]
5.4 Solving Linear Equations
MATLAB can easily be used to solve a large amount of linear equations using built-in functions.
Task 5: Linear Equations
Given the equations:
Set the equations on the following form:
Find and and define them in MATLAB.
Solve the equations, i.e., find
[End of Task]
When dealing with large matrices (finding inverse of A is time-consuming) or the inverse doesnt exist
other methods are used to find the solution, such as:
LU factorization
Singular value Decomposition
Etc.
In MATLAB we can also simply use the backslash operator \ in order to find the solution like this:
x = A\b
Example:
Given the following equations:
30 Linear Algebra; Vectors and Matrices
MATLAB Course - Part I: Introduction MATLAB Basics
From the equations we find:
[
]
[
]
As you can see, the matrix is not a quadratic matrix, meaning we cannot find the inverse of ,
thus
Below we see how the m-file for this function looks like:
You may define and in the Command window and the use the function on order to find :
>> A=[1 2;3 4];
>> b=[5;6];
>> x = linsolution(A,b)
x =
-4.0000
4.5000
After the function declaration (function [x] = linsolution(A,b)) in the m.file, you may
write a description of the function. This is done with the Comment sign % before each line.
From the Command window you can then type help <function name> in order to read this
information:
>> help linsolution
Solves the problem Ax=b using x=inv(A)*b
Created By Hans-Petter Halvorsen
[End of Example]
37 M-files; Scripts and user-define functions
MATLAB Course - Part I: Introduction MATLAB Basics
Naming a Function Uniquely:
To avoid choosing a name for a new function that might conflict with a name already in use, check
for any occurrences of the name using this command:
which -all functionname
Task 7: User-defined function
Create a function calc_average that finds the average of two numbers.
Test the function afterwards as follows:
>>x = 2;
>>y = 4;
>>z = calc_average(x,y)
[End of Task]
Task 8: User-defined function
Create a function circle that finds the area in a circle based on the input parameter (radius).
Run and test the function in the Command window.
[End of Task]
38
7 Plotting
Plotting is a very important and powerful feature in MATLAB. In this chapter we will learn the basic
plotting functionality in MATLAB.
Plots functions: Here are some useful functions for creating plots:
Function Description Example
plot
Generates a plot. plot(y) plots the columns of y against the
indexes of the columns.
>X = [0:0.01:1];
>Y = X.*X;
>plot(X, Y)
figure
Create a new figure window
>>figure
>>figure(1)
subplot
Create subplots in a Figure. subplot(m,n,p) or subplot(mnp),
breaks the Figure window into an m-by-n matrix of small axes,
selects the p-th axes for the current plot. The axes are counted
along the top row of the Figure window, then the second row,
etc.
>>subplot(2,2,1)
grid
Creates grid lines in a plot.
grid on adds major grid lines to the current plot.
grid off removes major and minor grid lines from the current
plot.
>>grid
>>grid on
>>grid off
axis
Control axis scaling and appearance. axis([xmin xmax ymin
ymax]) sets the limits for the x- and y-axis of the current axes.
>>axis([xmin xmax ymin ymax])
>>axis off
>>axis on
title
Add title to current plot
title('string')
>>title('this is a title')
xlabel
Add xlabel to current plot
xlabel('string')
>> xlabel('time')
ylabel
Add ylabel to current plot
ylabel('string')
>> ylabel('temperature')
legend
Creates a legend in the corner (or at a specified position) of the
plot
>> legend('temperature')
hold
Freezes the current plot, so that additional plots can be overlaid
>>hold on
>>hold off
Type help graphics in the Command Window for more information, or type help
<functionname> for help about a specific function.
Before you start, you should use the Help system in MATLAB to read more about these functions.
Type help <functionname> in the Command window.
Example:
Here we see some examples of how to use the different plot functions:
39 Plotting
MATLAB Course - Part I: Introduction MATLAB Basics
[End of Example]
Before you start using these functions, you should watch the video Using Basic Plotting
Functions.
The video is available from: http://home.hit.no/~hansha/?lab=matlab
Task 9: Plotting
In the Command window in MATLAB window input the time from seconds to
seconds in increments of seconds as follows:
>>t = [0:0.1:10];
Then, compute the output y as follows:
>>y = cos(t);
Use the Plot command:
>>plot(t,y)
[End of Task]
40 Plotting
MATLAB Course - Part I: Introduction MATLAB Basics
7.1 Plotting Multiple Data Sets in One Graph
In MATLAB it is easy to plot multiple data set in one graph.
Example:
x = 0:pi/100:2*pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y, x,y2, x,y3)
This gives the following plot:
Another approach is to use the hold command:
x=0:0.01:2*pi;
plot(x, sin(x))
hold on
plot(x, cos(x))
hold off
This gives the following plot:
41 Plotting
MATLAB Course - Part I: Introduction MATLAB Basics
[End of Example]
Task 10: Plot of dynamic system
Given the following differential equation:
where
Set and the initial condition
Create a Script in MATLAB (.m file) where you plot the solution in the time interval
Add Grid, and proper Title and Axis Labels to the plot.
[End of Task]
42 Plotting
MATLAB Course - Part I: Introduction MATLAB Basics
7.2 Displaying Multiple Plots in One Figure
Sub-Plots
The subplot command enables you to display multiple plots in the same window or print them on the
same piece of paper. Typing subplot(m,n,p) partitions the figure window into an m-by-n matrix of
small subplots and selects the pth subplot for the current plot. The plots are numbered along the first
row of the figure window, then the second row, and so on.
The syntax is as follows:
subplot(m,n,p)
Example:
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)
This gives:
43 Plotting
MATLAB Course - Part I: Introduction MATLAB Basics
[End of Example]
Task 11: Sub-plots
Plot Sin(x) and Cos(x) in 2 different subplots.
Add Titles and Labels.
[End of Task]
7.3 Custimizing
There is lots of customizing you can do with plots, e.g., you can add a title, x- and y-axis labels, add a
legend and customize line colors and line-styles.
The functions for doing this is; title, xlabel, ylabel, legend, etc.
Example:
x=0:0.1:2*pi;
plot(x, sin(x))
%Customize the Plot:
title('This is a Title')
xlabel('This is a X label')
ylabel('This is a y label')
legend('sin(x)')
grid on
44 Plotting
MATLAB Course - Part I: Introduction MATLAB Basics
This gives the following plot:
[End of Example]
For line colors and line-styles we have the following properties we can use for the plot function:
Line Styles:
Marker specifiers:
45 Plotting
MATLAB Course - Part I: Introduction MATLAB Basics
Colors:
Example:
>> x=0:0.1:2*pi;
>> plot(x, sin(x), 'r:o')
46 Plotting
MATLAB Course - Part I: Introduction MATLAB Basics
This gives the following plot:
[End of Example]
7.4 Other Plots
MATLAB offers lots of different plots.
Task 12: Other Plots
Check out the help for the following 2D functions in MATLAB: loglog, semilogx, semilogy, plotyy,
polar, fplot, fill, area, bar, barh, hist, pie, errorbar, scatter.
Try some of them, e.g., bar, hist and pie.
[End of Task]
47
8 Flow Control
8.1 Flow Control
You may use different loops in MATLAB
For loop
While loop
If you want to control the flow in your program, you may want to use one of the following:
If-else statement
Switch and case statement
It is assumed you know about For Loops, While Loops, If-Else and Switch statements from other
programming languages, so we will briefly show the syntax used in MATLAB and go through some
simple examples.
8.2 If-else Statement
The if statement evaluates a logical expression and executes a group of statements when the
expression is true. The optional elseif and else keywords provide for the execution of alternate
groups of statements. An end keyword, which matches the if, terminates the last group of
statements. The groups of statements are delineated by the four keywordsno braces or brackets
are involved.
The general syntax is as follows:
if expression1
statements1
elseif expression2
statements2
else
statements3
end
48 Flow Control
MATLAB Course - Part I: Introduction MATLAB Basics
Example:
Here are some simple code snippets using the if sentence:
n=5
if n > 2
M = eye(n)
elseif n < 2
M = zeros(n)
else
M = ones(n)
end
or:
n=5
if n == 5
M = eye(n)
else
M = ones(n)
end
Note! You have to use if n == 5 not if n = 5
[End of Example]
Example:
if A == B, ...
Note! If A and B are scalars this works but If A and B are matrices this might not work as expected!
Try it!
Use instead:
if isequal(A, B), ...
Try it!
[End of Example]
Operators:
You may use the following operators in MATLAB:
Mathematical Operator Description MATLAB Operator
Less Than <
Less Than or Equal To <=
Greater Than >
Greater Than or Equal To >=
49 Flow Control
MATLAB Course - Part I: Introduction MATLAB Basics
Equal To ==
Not Equal To ~=
Logical Operators:
You may use the following logical operators in MATLAB:
Logical Operator MATLAB Operator
AND &
OR |
Task 13: If-else Statements
Given the second order algebraic equation:
The solution (roots) is as follows:
{
where - there is no solution, - any complex number is a solution
Create a function that finds the solution for x based on different input values for a, b and c, e.g.,
function x = solveeq(a,b,c)
Use if-else statements to solve the problems
Test the function from the Command window to make sure it works as expected, e.g.,
>> a=0, b=2,c=1
>> solveeq(a,b,c)
Compare the results using the built-in function roots.
Tip! For , you can just type disp(there is no solution) and for you can type disp(any complex
number is a solution) or something like that.
[End of Task]
50 Flow Control
MATLAB Course - Part I: Introduction MATLAB Basics
8.3 Switch and Case Statement
The switch statement executes groups of statements based on the value of a variable or expression.
The keywords case and otherwise delineate the groups. Only the first matching case is executed.
There must always be an end to match the switch.
The general syntax is as follows:
Example:
n=2
switch(n)
case 1
M = eye(n)
case 2
M = zeros(n)
case 3
M = ones(n)
end
[End of Example]
Task 14: Switch-Case Statements
Create a function that finds either the Area or the circumference of a circle using a Switch-Case
statement
You can, e.g., call the function like this:
>> r=2;
switch variable
case case_value1
statements1
case case_value2
statements2
otherwise
statements
end
51 Flow Control
MATLAB Course - Part I: Introduction MATLAB Basics
>> calccircl(r,1) % 1 means area
>> calccircl(r,2) % 2 means circumference
[End of Task]
8.4 For loop
The For loop repeats a group of statements a fixed, predetermined number of times. A matching end
delineates the statements.
The general syntax is as follows:
Example:
m=5
for n = 1:m
r(n) = rank(magic(n));
end
r
[End of Example]
Task 15: Fibonacci Numbers
In mathematics, Fibonacci numbers are the numbers in the following sequence:
0, 1, 1, 2 ,3, 5, 8, 13, 21, 34, 55, 89, 144,
By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum
of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation:
for variable =
initval:endval
statement
...
statement
end
52 Flow Control
MATLAB Course - Part I: Introduction MATLAB Basics
with seed values:
Write a function in MATLAB that calculates the N first Fibonacci numbers, e.g.,
>> N=10;
>> fibonacci(N)
ans =
0
1
1
2
3
5
8
13
21
34
Use a For loop to solve the problem.
Fibonacci numbers are used in the analysis of financial markets, in strategies such as Fibonacci
retracement, and are used in computer algorithms such as the Fibonacci search technique and the
Fibonacci heap data structure. They also appear in biological settings, such as branching in trees,
arrangement of leaves on a stem, the fruitlets of a pineapple, the flowering of artichoke, an uncurling
fern and the arrangement of a pine cone.
[End of Task]
8.5 While loop
The while loop repeats a group of statements an indefinite number of times under control of a logical
condition. A matching end delineates the statements.
The general syntax is as follows:
Example:
m=5;
while expression
statements
end
53 Flow Control
MATLAB Course - Part I: Introduction MATLAB Basics
while m > 1
m = m - 1;
zeros(m)
end
[End of Example]
Task 16: While Loop
Create a Script or Function that creates Fibonacci Numbers up to a given number, e.g.,
>> maxnumber=2000;
>> fibonacci(maxnumber)
Use a While Loop to solve the problem.
[End of Task]
8.6 Additional Tasks
Here are some additional tasks about Loops and Flow control.
Task 17: For Loops
Extend your calc_average function from a previous task so it can calculate the average of a vector
with random elements. Use a For loop to iterate through the values in the vector and find sum in
each iteration:
mysum = mysum + x(i);
Test the function in the Command window
[End of Task]
Task 18: If-else Statement
Create a function where you use the if-else statement to find elements larger then a specific value
in the task above. If this is the case, discard these values from the calculated average.
Example discarding numbers larger than 10 gives:
x =
4 6 12
>> calc_average3(x)
54 Flow Control
MATLAB Course - Part I: Introduction MATLAB Basics
ans =
5
[End of Task]
55
9 Mathematics
MATLAB is a powerful tool for mathematical calculations.
Type help elfun (elementary functions) in the Command window for more information about basic
mathematical functions.
9.1 Basic Math Functions
Some Basic Math functions in MATLAB: exp, sqrt, log, etc. Look up these functions in the Help
system in MATLAB.
Task 19: Basic Math function
Create a function that calculates the following mathematical expression:
[End of Task]
9.2 Statistics
Some Statistics functions in MATLAB: mean, max, min, std, etc. Look up these functions in the
Help system in MATLAB.
Task 20: Statistics
Create a vector with random numbers between 0 and 100. Find the following statistics: mean,
median, standard deviation, minimum, maximum and the variance.
[End of Task]
9.3 Trigonometric Functions
MATLAB offers lots of Trigonometric functions, e.g., sin, cos, tan, etc. Look up these functions in
the Help system in MATLAB.
56 Mathematics
MATLAB Course - Part I: Introduction MATLAB Basics
Note! Most of the trigonometric functions require that the angle is expressed in radians.
Example:
>> sin(pi/4)
ans =
0.7071
[End of Example]
Task 21: Conversion
Since most of the trigonometric functions require that the angle is expressed in radians, we will
create our own functions in order to convert between radians and degrees.
It is quite easy to convert from radians to degrees or from degrees to radians. We have that:
[] []
This gives:
[] [] (
)
[] [] (
)
Create two functions that convert from radians to degrees (r2d(x)) and from degrees to radians
(d2r(x)) respectively.
Test the functions to make sure that they work as expected.
[End of Task]
Task 22: Trigonometric functions on right triangle
Given right triangle:
57 Mathematics
MATLAB Course - Part I: Introduction MATLAB Basics
Create a function that finds the angle (in degrees) based on input arguments ,
and respectively.
Use, e.g., a third input type to define the different types above.
Use you previous function r2d() to make sure the output of your function is in degrees and not in
radians.
Test the functions to make sure it works properly.
Tip! We have that:
)
[End of Task]
Task 23: Law of cosines
Given:
Create a function where you find c using the law of cosines.
Test the functions to make sure it works properly.
[End of Task]
Task 24: Plotting
58 Mathematics
MATLAB Course - Part I: Introduction MATLAB Basics
Plot and for in the same plot.
Make sure to add labels and a legend, and use different line styles and colors for the plots.
[End of Task]
9.4 Complex Numbers
Complex numbers are important in modelling and control theory.
A complex number is defined like this:
or
The imaginary unit or is defined as:
Where is called the real part of and is called the imaginary part of , i.e.:
,
You may also imaginary numbers on exponential/polar form:
where:
||
Note that and
59 Mathematics
MATLAB Course - Part I: Introduction MATLAB Basics
Rectangular form of a complex number Exponential/polar form of a complex number
Example:
Given the following complex number:
In MATLAB we may type:
>> z=2+3i
or:
>> z=2+3j
[End of Example]
The complex conjugate of z is defined as:
To add or subtract two complex numbers, we simply add (or subtract) their real parts and their
imaginary parts.
In Division and multiplication, we use the polar form.
Given the complex numbers:
and
Multiplication:
60 Mathematics
MATLAB Course - Part I: Introduction MATLAB Basics
Division:
MATLAB functions:
Some Basic functions for complex numbers in MATLAB: abs, angle, imag, real, conj, complex, etc.
Function Description Example
i,j
Imaginary unit. As the basic imaginary unit SQRT(-1), i and j are
used to enter complex numbers. For example, the expressions
3+2i, 3+2*i, 3+2j, 3+2*j and 3+2*sqrt(-1) all have the same
value.
>>z=2+4i
>>z=2+4j
abs
abs(x) is the absolute value of the elements of x. When x is
complex, abs(x) is the complex modulus (magnitude) of the
elements of X.
>>z=2+4i
>>abs(z)
angle
Phase angle. angle(z) returns the phase angles, in radians
>>z=2+4i
>>angle(z)
imag
Complex imaginary part. imag(z) is the imaginary part of z.
>>z=2+4i
>>b=imag(z)
real
Complex real part. real(z) is the real part of z.
>>z=2+4i
>>a=real(z)
conj
Complex conjugate. conj(x) is the complex conjugate of x.
>>z=2+4i
>>z_con=conj(z)
complex
Construct complex result from real and imaginary parts. c =
complex(a,b) returns the complex result A + Bi
>>a=2;
>>b=3;
>>z=complex(a,b)
Look up these functions in the Help system in MATLAB.
Task 25: Complex numbers
Given two complex numbers
Find the real and imaginary part of c and d in MATLAB.
Use MATLAB to find .
Use the direct method supported by MATLAB and the specific complex functions abs, angle, imag,
real, conj, complex, etc. together with the formulas for complex numbers that are listed above in the
text (as you do it when you should calculate it using pen & paper).
Find also and . Find also the complex conjugate.
[End of Task]
61 Mathematics
MATLAB Course - Part I: Introduction MATLAB Basics
Task 26: Complex numbers
Find the roots of the equation:
We can e.g., use the solveeq function we created in a previous task. Compare the results using the
built-in function roots.
Discuss the results.
Add the sum of the roots.
[End of Task]
9.5 Polynomials
A polynomial is expressed as:
where
In MATLAB we write:
>> p=[-5.45 0 3.2 8 5.8]
p =
-5.4500 0 3.2000 8.0000 5.8000
[End of Example]
MATLAB offers lots of functions on polynomials, such as conv, roots, deconv, polyval, polyint,
polyder, polyfit, etc. Look up these functions in the Help system in MATLAB.
Task 27: Polynomials
Define the following polynomial in MATLAB:
62 Mathematics
MATLAB Course - Part I: Introduction MATLAB Basics
Find the roots of the polynomial ( ) (and check if the answers are correct)
Find
Use the polynomial functions listed above.
[End of Task]
Task 28: Polynomials
Given the following polynomials:
Find the polynomial
, i.e.,
Use the polynomial functions listed above.
[End of Task]
Task 29: Polynomial Fitting
Find the 6.order Polynomial that best fits the following function:
Use the polynomial functions listed above.
Plot both the function and the 6. order Polynomial to compare the results.
[End of Task]
63
10 Additional Tasks
If you have time left or need more practice, solve the tasks below.
Task 30: User-defined function
Create a function that uses Pythagoras to calculate the hypotenuse of a right-angled triangle, e.g.:
function h = pyt(a,b)
% ..
h =
Pythagoras theorem is as follows:
Note! The function should handle that and could be vectors.
[End of Task]
Task 31: MATLAB Script
Given the famous equation from Albert Einstein:
The sun radiates
[End of Task]
Task 32: Cylinder surface area
Create a function that finds the surface area of a cylinder based on the height (h) and the radius (r) of
the cylinder.
[End of Task]
Task 33: Create advanced expressions in MATLAB
Create the following expression in MATLAB:
Given
Find
(The answer should be )
Tip! You should split the expressions into different parts, such as:
poly =
num =
den =.
f =
65 Additional Tasks
MATLAB Course - Part I: Introduction MATLAB Basics
This makes the expression simpler to read and understand, and you minimize the risk of making an
error while typing the expression in MATLAB.
[End of Task]
Task 34: Solving Equations
Find the solution(s) for the given equations:
[End of Task]
Task 35: Preallocating of variables and vectorization
Here we will use preallocating of variables and vectorization and compare with using a For Loop.
We will use the functions tic and toc to find the execution time.
We will create a simple program that calculates for t=1 to 100 000.
Create the following Script:
% Test 1: Using a For Loop
clear
tic
tmax=100000;
for t=1:tmax
y(t,1)=cos(t);
end
toc
What was the execution time?
We will improve the Script by preallocating space for the variable y. Create the following Script:
% Test 2: For Lopp with preallocating
clear
tic
tmax=100000;
y=zeros(tmax,1); % preallocating
66 Additional Tasks
MATLAB Course - Part I: Introduction MATLAB Basics
for t=1:tmax
y(t,1)=cos(t);
end
toc
What was the execution time?
We will improve the Script further by removing the For Loop by using vectorization instead:
% Test 3: Vectorization
clear
tic
tmax=100000;
t=1:tmax; %vectorization
y=cos(t);
toc
What was the execution time?
Discuss the result.
[End of Task]
Task 36: Nested For Loops
Given the matrices
and
, then
where
In MATLAB it is easy to multiply two matrices:
>> A=[0 1;-2 -3]
A =
0 1
-2 -3
>> B=[1 0;3 -2]
B =
1 0
3 -2
67 Additional Tasks
MATLAB Course - Part I: Introduction MATLAB Basics
>> A*B
ans =
3 -2
-11 6
But her you will create your own function that multiply two matrices:
function C = matrixmult(A,B)
Tip! You need to use 3 nested For Loops.
[End of Task]
68
Appendix A: MATLAB
Functions
This Appendix gives an overview of the most used functions in this course.
Built-in Constants
MATLAB have several built-in constants. Some of them are explained here:
Name Description
i, j
Used for complex numbers, e.g., z=2+4i
pi
inf
, Infinity
NaN
Not A Number. If you, e.g., divide by zero, you get NaN
Basic Functions
Here are some descriptions for the most used basic MATLAB functions.
Function Description Example
help
MATLAB displays the help information available
>>help
help
<function>
Display help about a specific function
>>help plot
who, whos
who lists in alphabetical order all variables in the currently
active workspace.
>>who
>>whos
clear
Clear variables and functions from memory.
>>clear
>>clear x
size
Size of arrays, matrices
>>x=[1 2 ; 3 4];
>>size(A)
length
Length of a vector
>>x=[1:1:10];
>>length(x)
format
Set output format
disp
Display text or array
>>A=[1 2;3 4];
>>disp(A)
plot
This function is used to create a plot
>>x=[1:1:10];
>>plot(x)
>>y=sin(x);
>>plot(x,y)
clc
Clear the Command window
>>cls
rand
Creates a random number, vector or matrix
>>rand
>>rand(2,1)
max
Find the largest number in a vector
>>x=[1:1:10]
>>max(x)
min
Find the smallest number in a vector
>>x=[1:1:10]
>>min(x)
69 Appendix A: MATLAB Functions
MATLAB Course - Part I: Introduction MATLAB Basics
mean
Average or mean value
>>x=[1:1:10]
>>mean(x)
std
Standard deviation
>>x=[1:1:10]
>>std(x)
Linear Algebra
Here are some useful functions for Linear Algebra in MATLAB:
Function Description Example
rank
Find the rank of a matrix. Provides an estimate of the number of
linearly independent rows or columns of a matrix A.
>>A=[1 2; 3 4]
>>rank(A)
det
Find the determinant of a square matrix
>>A=[1 2; 3 4]
>>det(A)
inv
Find the inverse of a square matrix
>>A=[1 2; 3 4]
>>inv(A)
eig
Find the eigenvalues of a square matrix
>>A=[1 2; 3 4]
>>eig(A)
ones
Creates an array or matrix with only ones
>>ones(2)
>>ones(2,1)
eye
Creates an identity matrix
>>eye(2)
diag
Find the diagonal elements in a matrix
>>A=[1 2; 3 4]
>>diag(A)
Type help matfun (Matrix functions - numerical linear algebra) in the Command Window for more
information, or type help elmat (Elementary matrices and matrix manipulation).
You may also type help <functionname> for help about a specific function.
Plotting
Plots functions: Here are some useful functions for creating plots:
Function Description Example
plot
Generates a plot. plot(y) plots the columns of y against the
indexes of the columns.
>X = [0:0.01:1];
>Y = X.*X;
>plot(X, Y)
figure
Create a new figure window
>>figure
>>figure(1)
subplot
Create subplots in a Figure. subplot(m,n,p) or subplot(mnp),
breaks the Figure window into an m-by-n matrix of small axes,
selects the p-th axes for the current plot. The axes are counted
along the top row of the Figure window, then the second row,
etc.
>>subplot(2,2,1)
grid
Creates grid lines in a plot.
grid on adds major grid lines to the current plot.
grid off removes major and minor grid lines from the current
plot.
>>grid
>>grid on
>>grid off
axis
Control axis scaling and appearance. axis([xmin xmax ymin
ymax]) sets the limits for the x- and y-axis of the current axes.
>>axis([xmin xmax ymin ymax])
>>axis off
>>axis on
title
Add title to current plot
title('string')
>>title('this is a title')
xlabel
Add xlabel to current plot
xlabel('string')
>> xlabel('time')
ylabel
Add ylabel to current plot
>> ylabel('temperature')
70 Appendix A: MATLAB Functions
MATLAB Course - Part I: Introduction MATLAB Basics
ylabel('string')
legend
Creates a legend in the corner (or at a specified position) of the
plot
>> legend('temperature')
hold
Freezes the current plot, so that additional plots can be overlaid
>>hold on
>>hold off
Type help graphics in the Command Window for more information, or type help
<functionname> for help about a specific function.
Operators:
You may use the following operators in MATLAB:
Mathematical Operator Description MATLAB Operator
Less Than <
Less Than or Equal To <=
Greater Than >
Greater Than or Equal To >=
Equal To ==
Not Equal To ~=
Logical Operators
You may use the following logical operators in MATLAB:
Logical Operator MATLAB Operator
AND &
OR |
Complex Numbers
Functions used to create or manipulate complex numbers.
Function Description Example
i,j
Imaginary unit. As the basic imaginary unit SQRT(-1), i and j are
used to enter complex numbers. For example, the expressions
3+2i, 3+2*i, 3+2j, 3+2*j and 3+2*sqrt(-1) all have the same
value.
>>z=2+4i
>>z=2+4j
abs
abs(x) is the absolute value of the elements of x. When x is
complex, abs(x) is the complex modulus (magnitude) of the
elements of X.
>>z=2+4i
>>abs(z)
angle
Phase angle. angle(z) returns the phase angles, in radians
>>z=2+4i
>>angle(z)
imag
Complex imaginary part. imag(z) is the imaginary part of z.
>>z=2+4i
>>b=imag(z)
real
Complex real part. real(z) is the real part of z.
>>z=2+4i
>>a=real(z)
conj
Complex conjugate. conj(x) is the complex conjugate of x.
>>z=2+4i
>>z_con=conj(z)
complex
Construct complex result from real and imaginary parts. c =
complex(a,b) returns the complex result A + Bi
>>a=2;
>>b=3;
71 Appendix A: MATLAB Functions
MATLAB Course - Part I: Introduction MATLAB Basics
>>z=complex(a,b)
Telemark University College
Faculty of Technology
Kjlnes Ring 56
N-3918 Porsgrunn, Norway
www.hit.no
Hans-Petter Halvorsen, M.Sc.
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
E-mail: [email protected]
Blog: http://home.hit.no/~hansha/
Room: B-237a