Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 68

Introduction to Matlab

Outline:
 What is Matlab?
• Matlab Screen
• Variables, array, matrix, indexing
• Operators (Arithmetic, relational, logical )
• Display Facilities
• Flow Control
• Using of M-File
• Writing User Defined Functions
• Conclusion
• MATLAB stands for Matrix Laboratory.
• Matlab had many functions and toolboxes to
help in various applications
• It allows you to solve many technical
computing problems, especially those with
matrix and vector formulas, in a fraction of the
time it would take to write a program in a
scalar non-interactive language such as C or
Fortran.
What is Matlab?
• Matlab is basically a high level language which
has many specialized toolboxes for making
things easier for us
• How high?
Matlab

High Level
Languages such as
C, Pascal etc.

Assembly
What are we interested in?
• Matlab is too broad for our purposes in this
course.
• The features we are going to require is
Matlab
Series of
Matlab
commands
Command
m-files mat-files
Line

functions Command execution Data


Input like DOS command storage/
Output window loading
capability
The MATLAB System
MATLAB system consists of these main parts:
• Desktop Tools and Development Environment
– Includes the MATLAB desktop and Command Window,
an editor and debugger, a code analyzer, browsers for
viewing help, the workspace, files, and other tools
• Mathematical Function Library
– vast collection of computational algorithms ranging from
elementary functions, like sine, cosine, and complex
arithmetic, to more sophisticated functions like matrix
inverse, matrix eigenvalues, Bessel functions, and fast
Fourier transforms.
• The Language
– The MATLAB language is a high-level matrix/array language with
control flow statements, functions, data structures,
input/output, and object-oriented programming features.
• Graphics
– MATLAB has extensive facilities for displaying vectors and
matrices as graphs, as well as editing and printing these graphs.
It also includes functions that allow you to customize the
appearance of graphics as well as build complete graphical user
interfaces on your MATLAB applications.
• External Interfaces
– The external interfaces library allows you to write C and Fortran
programs that interact with MATLAB.
Main Matlab Window
Matlab Screen
• Command Window
– type commands

• Current Directory
– View folders and m-files

• Workspace
– View program variables
– Double click on a variable
to see it in the Array Editor

• Command History
– view past commands
– save a whole session
using diary
Variables
• No need for types. i.e.,

int a;
double b;
float c;
• All variables are created with double precision unless
specified and they are matrices.

Example:
>>x=5;
>>x1=2;

• After these statements, the variables are 1x1 matrices with


double precision
Array, Matrix
• a vector x = [1 2 5 1]

x =
1 2 5 1

• a matrix x = [1 2 3; 5 1 4; 3 2 -1]

x =
1 2 3
5 1 4
3 2 -1

• transpose y = x’ y =
1
2
5
1
Long Array, Matrix
• t =1:10

t =
1 2 3 4 5 6 7 8 9 10
• k =2:-0.5:-1

k =
2 1.5 1 0.5 0 -0.5 -1

• B = [1:4; 5:8]

x =
1 2 3 4
5 6 7 8
Generating Vectors from functions
• zeros(M,N) MxN matrix of zeros x = zeros(1,3)
x =
0 0 0
• ones(M,N) MxN matrix of ones
x = ones(1,3)
x =
1 1 1
• rand(M,N) MxN matrix of uniformly
distributed x = rand(1,3)
random
x =
numbers on (0,1)
0.9501 0.2311 0.6068
Matrix Index
• The matrix indices begin from 1 (not 0 (as in C))
• The matrix indices must be positive integer
Given:

A(-2), A(0)

Error: ??? Subscript indices must either be real positive integers or logicals.

A(4,2)
Error: ??? Index exceeds matrix dimensions.
Concatenation of Matrices
• x = [1 2], y = [4 5], z=[ 0 0]

A = [ x y]

1 2 4 5

B = [x ; y]

1 2
4 5

C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent.
Operators (arithmetic)
+ addition
- subtraction
* multiplication
/ division
^ power
‘ complex conjugate transpose
Matrices Operations

Given A and B:

Addition Subtraction Product Transpose


Operators (Element by Element)

.*element-by-element multiplication
./ element-by-element division
.^element-by-element power
The use of “.” – “Element”
A = [1 2 3; 5 1 4; 3 2 1] Operation
A=
1 2 3
5 1 4
3 2 -1

b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 8 -3 0.33 0.5 -3 1 4 9
1 2 3 3 4 -1
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
Operators (relational, logical)
• == Equal to
• ~= Not equal to
• < Strictly smaller
• > Strictly greater
• <= Smaller than or equal to
• >= Greater than equal to
• & And operator
• | Or operator
Flow Control
• if
• for
• while
• break
• ….
Control Structures
Some Dummy Examples
• If Statement Syntax
if ((a>3) & (b==5))
Some Matlab Commands;
if (Condition_1) end
Matlab Commands
if (a<3)
elseif (Condition_2) Some Matlab Commands;
Matlab Commands elseif (b~=5)
elseif (Condition_3) Some Matlab Commands;
end
Matlab Commands
else if (a<3)
Some Matlab Commands;
Matlab Commands else
end Some Matlab Commands;
end
Control Structures
Some Dummy Examples
• For loop syntax for i=1:100
Some Matlab Commands;
end

for i=Index_Array for j=1:3:200


Some Matlab Commands;
Matlab Commands end

end for m=13:-0.2:-21


Some Matlab Commands;
end

for k=[0.1 0.3 -13 12 7 -9.3]


Some Matlab Commands;
end
Control Structures
• While Loop Syntax

Dummy Example
while (condition)
while ((a>3) & (b==5))
Matlab Commands Some Matlab Commands;
end
end
Working with Matrices and Arrays
• Since Matlab makes extensive use of matrices,
the best way for you to get started with
MATLAB is to learn how to handle matrices.
– Separate the elements of a row with blanks or commas.
– Use a semicolon ; to indicate the end of each row.
– Surround the entire list of elements with square brackets, [ ].

A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]


• MATLAB displays the matrix you just entered:
A=
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
• Once you have entered the matrix, it is automatically
remembered in the MATLAB workspace. You can
simply refer to it as A.
• Keep in mind, variable names are case-sensitive
• When you do not specify an output variable,
MATLAB uses the variable ans, short for answer,
to store the results of a calculation.
• Subscripts
The element in row i and column j of A
is given by A(i,j).
So to compute the sum of the elements in the fourth
column of A, we have:
A(1,4) + A(2,4) + A(3,4) + A(4,4)
Which produces:
ans = 34
• The Colon Operator
• For example: 1:10
is a row vector containing the integers from 1 to 10:
1 2 3 4 5 6 7 8 9 10

• To obtain non-unit spacing, specify an increment. For


example: 100:-7:50 will give you
100 93 86 79 72 65 58 51

• Subscript expressions involving colons refer to portions


of a matrix. For example: A(1:k,j)
refers to the first k elements of the jth column of A.
• Numbers
MATLAB uses conventional decimal notation, with an
optional decimal point and leading plus or minus sign, for
numbers. Scientific notation uses the letter e to specify
the power. Imaginary numbers use either i or j as a
suffix. Examples of legal numbers are:
3 -99 0.0001
9.6397238 1.60210e-20 6.02252e23
1i -3.14159j 3e5i

MATLAB software stores the real and imaginary parts


of a complex number.
• The Load Function
The load function reads binary files containing matrices
generated by earlier MATLAB sessions, or reads text files
containing numeric data.

• M-Files
You can create your own programs using M-files, which
are plain text files containing MATLAB code. Use the
MATLAB Editor or another text editor to create a file
containing the same statements you would type at the
MATLAB command line. Save the file under a name that
ends in .m
• Arrays
Arithmetic operations on arrays are done element by
element. This means that addition and subtraction are the
same for arrays and matrices, but that multiplicative
operations are different. MATLAB uses a dot, or decimal
point, as part of the notation for multiplicative array
operations.
Example: A.*A
the result is an array containing the squares of the integers
ans =
256 9 4 169
25 100 121 64
81 36 49 144
16 225 196 1
• Multivariate Data
MATLAB uses column-oriented analysis for multivariate statistical
data. Each column in a data set represents a variable and each row
an observation. The (i,j)th element is the ith observation of the jth
variable.

As an example, consider a data set with three variables:


• Heart rate • Weight • Hours exercise per week

For five observations, the resulting array might look like


• D = [ 72 134 3.2
81 201 3.5
69 156 7.1
82 148 2.4
75 170 1.2 ]
• Now you can apply MATLAB analysis functions to this data
set. For example, to obtain the mean and standard
deviation of each column, use
mu = mean(D), sigma = std(D)
mu = 75.8 161.8 3.48
sigma = 5.6303 25.499 2.2107

• Entering Long Statements


If a statement does not fit on one line, use an ellipsis
(three periods), ... , followed by Return or Enter to indicate
that the statement continues on the next line. For example,
s = 1 -1/2 + 1/3 -1/4 + 1/5 - 1/6 + 1/7 ...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;
Graphics
• MATLAB provides a variety of techniques to
display data graphically.
• Interactive tools enable you to manipulate
graphs to achieve results that reveal the most
information about your data.
• You can also edit and print graphs for
presentations, or export graphs to standard
graphics formats for presentation in Web
browsers or other media.
Basic Task: Plot the function sin(x)
between 0≤x≤4π
• Create an x-array of 100 samples between 0 and
4π.

>>x=linspace(0,4*pi,100);

• Calculate sin(.) of the x-array 1

0.8

0.6

>>y=sin(x); 0.4

0.2

• Plot the y-array


-0.2

-0.4

-0.6

>>plot(y) -0.8

-1
0 10 20 30 40 50 60 70 80 90 100
Plot the function e-x/3sin(x) between
0≤x≤4π
• Create an x-array of 100 samples between 0
and 4π.
>>x=linspace(0,4*pi,100);

• Calculate sin(.) of the x-array


>>y=sin(x);

• Calculate e-x/3 of the x-array


>>y1=exp(-x/3);

• Multiply the arrays y and y1


>>y2=y*y1;
Plot the function e-x/3sin(x) between
0≤x≤4π
• Multiply the arrays y and y1 correctly
>>y2=y.*y1;

• Plot the y2-array


0.7

>>plot(y2) 0.6

0.5

0.4

0.3

0.2

0.1

-0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100
Display Facilities
0.7

0.6

• plot(.)
0.5

0.4

0.3

Example:
0.2

0.1
>>x=linspace(0,4*pi,100); 0

>>y=sin(x); -0.1

>>plot(y) -0.2

>>plot(x,y) -0.3
0 10 20 30 40 50 60 70 80 90 100

0.7

• stem(.) 0.6

0.5

0.4

0.3

Example:
0.2

0.1
>>stem(y) 0

>>stem(x,y) -0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100
Display Facilities
• title(.)
This is the sinus function
>>title(‘This is the sinus function’) 1

0.8

• xlabel(.) 0.6

0.4

>>xlabel(‘x (secs)’) 0.2

sin(x)
0

• ylabel(.)
-0.2

-0.4

-0.6

-0.8
>>ylabel(‘sin(x)’) -1
0 10 20 30 40 50 60 70 80 90 100
x (secs)
Basic Plotting Functions
• The plot function has different forms, depending on the input
arguments.
• If y is a vector, plot(y) produces a piecewise graph of the
elements of (y) versus the index of the elements of (y).
• If you specify two vectors as arguments, plot(x,y) produces a
graph of y versus x.
• You can also label the axes and add a title, using the ‘xlabel’,
‘ylabel’, and ‘title’ functions.
Example: xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)
• Plotting Multiple Data Sets in One Graph
– Multiple x-y pair arguments create multiple graphs with a
single call to plot.
For 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)
• Specifying Line Styles and Colors
It is possible to specify color, line styles, and markers
(such as plus signs or circles) when you plot your data
using the plot command:
plot(x,y,'color_style_marker')

For example: plot(x,y,'r:+')


plots a red-dotted line and places plus sign markers at
each data point.
• Graphing Imaginary and Complex Data
When the arguments to plot are complex, the imaginary
part is ignored except when you use a single complex
argument.
For example: plot(Z)
which is equivalent to: plot(real(Z),imag(Z))

Adding Plots to an Existing Graph


When you type: hold on

MATLAB does not replace the existing graph when you


issue another plotting command; it adds the new data to
the current graph, rescaling the axes if necessary.
• Figure Windows
Graphing functions automatically open a new figure
window if there are no figure windows already on the
screen.

To make a figure window the current figure, type


figure(n)
where n is the number in the figure title bar. The
results of subsequent graphics commands are
displayed in this window.
• Displaying Multiple Plots in One Figure
subplot(m,n,p)
This splits the figure window into an m-by-n matrix of small
subplots and selects the pth subplot for the current plot.

• 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)
Controlling the Axes
• Setting Axis Limits & Grids
The axis command lets you to specify your own limits:
axis([xmin xmax ymin ymax])

You can use the axis command to make the axes visible
or invisible: axis on / axis off

The grid command toggles grid lines on and off:


grid on / grid off
Programming in Matlab
• Conditional Control
- if, else, elseif
- switch, case
• Loop Control
- for, while, continue, break
• Error Control
- try, catch
• Program Termination
- return
Multidimensional Arrays
• One way of creating a multidimensional array is by
calling zeros, ones, rand, or randn with more than
two arguments.
For example: R = randn(3,4,5);
creates a 3-by-4-by-5 array with a total of 3*4*5 = 60
normally distributed random elements.
Scripts and Functions
• There are two kinds of M-files:
- Scripts, which do not accept input arguments or return
output arguments. They operate on data in the
workspace. Any variables that they create remain in the
workspace, to be used in subsequent computations

- Functions, which can accept input arguments and


return output arguments. Internal variables are local to
the function.
Use of M-File
Click to create
a new M-File

• Extension “.m”
• A text file containing script or function or program to run
Use of M-File
Save file as Denem430.m

If you include “;” at the


end of each statement,
result will not be shown
immediately
• Global Variables
• If you want more than one function to share a
single copy of a variable, simply declare the variable
as global in all the functions. The global declaration
must occur before the variable is actually used in a
function.
Example: function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
Writing User Defined Functions
• Functions are m-files which can be executed by specifying
some inputs and supply some desired outputs.
• The code telling the Matlab that an m-file is actually a function
is
function out1=functionname(in1)
function out1=functionname(in1,in2,in3)
function [out1,out2]=functionname(in1,in2)

• You should write this command at the beginning of the m-file


and you should save the m-file with a file name same as the
function name
Writing User Defined Functions
• Examples
– Write a function : out=squarer (A, ind)
• Which takes the square of the input matrix if the input
indicator is equal to 1
• And takes the element by element square of the input matrix
if the input indicator is equal to 2

Same Name

Writing User Defined Functions
Another function which takes an input array and returns the sum and product of its
elements as outputs

• The function sumprod(.) can be called from command window or an m-file as


Graphical User Interfaces
• GUIDE, the MATLAB Graphical User Interface
Development Environment, provides a set of tools
for creating graphical user interfaces (GUIs). These
tools greatly simplify the process of designing and
building GUIs. You can use the GUIDE tools to
perform the following tasks:
- Laying out the GUI.
- Programming the GUI.
Example template for a push button
Notes:
• “%” is the neglect sign for Matlab (equaivalent
of “//” in C). Anything after it on the same line
is neglected by Matlab compiler.
• Sometimes slowing down the execution is
done deliberately for observation purposes.
You can use the command “pause” for this
purpose
pause %wait until any key
pause(3) %wait 3 seconds
Useful Commands

• The two commands used most by Matlab


users are
>>help functionname

>>lookfor keyword
DATA ANALYSIS
AND STATISTICS

61
Basic Data
Analysis
• Import data set
• Scatter plot

62
Basic Data Analysis (continued)
• Covariance and Correlation

Covariance and Correlation Coefficient Function Summary


Functio Description
n
cov Variance of vector - measure of spread or dispersion of sample variable.
Covariance of matrix - measure of strength of linear relationships between variables.
corrcoef Correlation coefficient - normalized measure of linear relationship strength between
variables.

• Example

63
Preprocessing
• Missing Values
You should remove NaN (The special value, NaN, stands for Not-a-
Number in MATLAB)s from the data before performing statistical
computations.

64
Preprocessing (continued)
• Removing Outliers
You can remove outliers or misplaced data points from a data
set in much the same manner as NaNs.
1. Calculate the mean and standard deviation from the data set.
2. Get the column of points that lies outside the 3*std.
3. Remove these points

Example

65
Regression and Curve Fitting
• You can find these coefficients efficiently by using the
MATLAB backslash operator.
Example: Ordinary least squares
y=b0+b1x
• Polynomial Regression
Example:
• Linear-in-the-Parameters Regression
Example:
• Multiple Regression
Example:

66
Questions
• ?
• ?
• ?
• ?
• ?
Thank You…

You might also like