SlideShare a Scribd company logo
Introduction to MATLAB
Originally created by
Kristian Sandberg
Department of Applied Mathematics
University of Colorado
Updated for compatibility with Release 13 by
Grady Wright
Department of Mathematics
University of Utah
Goal
The goal of this tutorial is to give a brief introduction to the mathematical software MATLAB.
After completing the worksheet you should know how to start MATLAB, how to use the
elementary functions in MATLAB and how to use MATLAB to plot functions.
What is MATLAB?
MATLAB is widely used in all areas of applied mathematics, in education and research at
universities, and in the industry. MATLAB stands for MATrix LABoratory and the software is
built up around vectors and matrices. This makes the software particularly useful for linear
algebra but MATLAB is also a great tool for solving algebraic and differential equations and for
numerical integration. MATLAB has powerful graphic tools and can produce nice pictures in
both 2D and 3D. It is also a programming language, and is one of the easiest programming
languages for writing mathematical programs. MATLAB also has some tool boxes useful for
signal processing, image processing, optimization, etc.
How to start MATLAB
Mac: Double-click on the icon for MATLAB.
PC: Choose the submenu "Programs" from the "Start" menu. From the "Programs" menu, open
the "MATLAB" submenu. From the "MATLAB" submenu, choose "MATLAB".
Unix: At the prompt, type matlab.
You can quit MATLAB by typing exit in the command window.
The MATLAB environment
Note: From now on an instruction to press a certain key will be denoted by < >, e.g., pressing the
enter key will be denoted as <enter>. Commands that should be typed at the prompt, will be
written in courier font.
The MATLAB environment (on most computer systems) consists of menus, buttons and a
writing area similar to an ordinary word processor. There are plenty of help functions that you
are encouraged to use. The writing area that you will see when you start MATLAB, is called the
command window. In this window you give the commands to MATLAB. For example, when you
want to run a program you have written for MATLAB you start the program in the command
window by typing its name at the prompt. The command window is also useful if you just want
to use MATLAB as a scientific calculator or as a graphing tool. If you write longer programs,
you will find it more convenient to write the program code in a separate window, and then run it
in the command window (discussed in Intro to programming).
In the command window you will see a prompt that looks like >> . You type your commands
immediately after this prompt. Once you have typed the command you wish MATLAB to
perform, press <enter>. If you want to interupt a command that MATLAB is running, type
<ctrl> + < c>.
The commands you type in the command window are stored by MATLAB and can be viewed in
the Command History window. To repeat a command you have already used, you can simply
double-click on the command in the history window, or use the <up arrow> at the command
prompt to iterate through the commands you have used until you reach the command you desire
to repeat.
Useful functions and operations in MATLAB
Using MATLAB as a calculator is easy.
Example: Compute 5 sin(2.53-pi)+1/75. In MATLAB this is done by simply typing
5*sin(2.5^(3-pi))+1/75
at the prompt. Be careful with parantheses and don't forget to type * whenever you multiply!
Note that MATLAB is case sensitive. This means that MATLAB knows a difference between
letters written as lower and upper case letters. For example, MATLAB will understand sin(2)
but will not understand Sin(2).
Here is a table of useful operations, functions and constants in MATLAB.
Operation, function or constant
MATLAB
command
+ (addition) +
- (subtraction) -
× (multiplication) *
/ (division) /
|x| (absolute value of x) abs(x)
square root of x sqrt(x)
ex exp(x)
ln x (natural log) log(x)
log10 x (base 10 log) log10(x)
sin x sin(x)
cos x cos(x)
tan x tan(x)
cot x cot(x)
arcsin x asin(x)
arccos x acos(x)
arctan x atan(x)
arccot x acot(x)
n! (n factorial) gamma(n+1)
e (2.71828...) exp(1)
 (3.14159265...) pi
i (imaginary unit, sqrt(-1)) i
Exercises
Compute the following expressions using MATLAB:
 3cos(pi)
 1+1+1/2+1/6+1/24-e
 ln (1000+2pi-2)
 e i pi
 The number of combinations in which 12 persons can stand in line. (Hint: Use factorials.)
Obtaining Help on MATLAB commands
To obtain help on any of the MATLAB commands, you simply need to type
help <command>
at the command prompt. For example, to obtain help on the gamma function, we type at the
command prompt:
help gamma
Try this now. You may also get help about commands using the "Help Desk", which can be
accessed by selecting the MATLAB Help option under the Help menu.
Note that the description MATLAB returns about the command you requested help on contains
the command name in ALL CAPS. This does not mean that you use this command by typing it in
ALL CAPS. In MATLAB, you almost always use all lower case letters when using a command.
Variables in MATLAB
We can easily define our own variables in MATLAB. Let's say we need to use the value of
3.5sin(2.9) repeatedly. Instead of typing 3.5*sin(2.9)over and over again, we can denote this
variable as x by typing the following:
x=3.5*sin(2.9)
(Please try this in MATLAB.) Now type
x+1
and observe what happens. Note that we did not need to declare x as a variable that is supposed
to hold a floating point number as we would need to do in most programming languages.
Often, we may not want to have the result of a calculation printed-out to the command window.
To supress this output, we put a semi-colon at the end of the command; MATLAB still performs
the command in "the background". If you defined x as above, now type
y=2*x;
y
and observe what happened.
In many cases we want to know what variables we have declared. We can do this by typing
whos. Alternatively, we can view the values by openning the "Workspace" window. This is done
by selecting the Workspace option from the View menu. If you want to erase all variables from
the MATLAB memory, type clear. To erase a specific variable, say x, type clear x. To clear
two specific variables, say x and y, type clear x y, that is separate the different variables with a
space. Variables can also be cleared by selecting them in the Workspace window and selecting
the delete option.
Vectors and matrices in MATLAB
We create a vector in MATLAB by putting the elements within [] brackets.
Example: x=[ 1 2 3 4 5 6 7 8 9 10]
We can also create this vector by typing x=1:10. The vector (1 1.1 1.2 1.3 1.4 1.5) can be
created by typing x=[ 1 1.1 1.2 1.3 1.4 1.5 ] or by typing x=1:0.1:1.5.
Matrices can be created according to the following example. The matrix A= is
created by typing
A=[1 2 3 ; 4 5 6; 7 8 9],
i.e., rows are separated with semi-colons. If we want to use a specific element in a vector or a
matrix, study the following example:
Example:
x=[10 20 30]
A=[ 1 2 3 ; 4 5 6 ; 7 8 9]
x(2)
A(3,1)
Here we extracted the second element of the vector by typing the variable and the position within
parantheses. The same principle holds for matrices; the first number specifies the row of the
matrix, and the second number specifies the column of the matrix. Note that in MATLAB the
first index of a vector or matrix starts at 1, not 0 as is common with other programming
languages.
If the matrices (or vectors which are special cases of a matrices) are of the same dimensions then
matrix addition, matrix subtraction and scalar multiplication works just like we are used to.
Example: Type
x=[1 2 3]
y =[4 5 6]
a=2
x+y
x-y
a*x
and observe what happens.
If want to apply an operation such as squaring each element in a matrix we have to use a dot .
before the operation we wish to apply. Type the following commands in MATLAB.
x=1:10
x.^2
A=[1 2 3 ; 4 5 6 ; 7 8 9 ]
A.^2
A^2
and observe the result. The dot allows us to do operations elementwise. All built-in functions
such as sin, cos, exp and so on automatically act elementwise on a matrix. Type
y=[0 1/4 1/2 3/4 1]
y=pi*y
sin(y)
and observe the result.
How to plot with MATLAB
There are different ways of plotting in MATLAB. The following two techniques, illustrated by
examples, are probably the most useful ones.
Example 1: Plot sin(x2) on the interval [-5,5]. To do this, type the following:
x=-5:0.01:5;
y=sin(x.^2);
plot(x,y)
and observe what happens.
Example 2: Plot exp(sin(x)) on the interval [-,]. To do this, type the following:
x=linspace(-pi,pi,101);
y=exp(sin(x));
plot(x,y)
and observe what happens. The command linspace creates a vector of 101 equally spaced
values between - and  (inclusive).
Ocassionally, we need to plot values that vary quite differently in magnitude. In this case, the
regular plot command fails to give us an adequate graphical picture of our data. Instead, we
need a command that plots values on a log scale. MATLAB has 3 such commands:
loglog,semilogx, and semilogy. Use the help command to see a description of each function.
As an example of where we may want to use one of these plotting routines, consider the
following problem:
Example 3: Plot x5/2 for x = 10-5 to 105. To do this, type the following:
x=logspace(-5,5,101);
y=x.^(5/2);
plot(x,y)
and observe what happens. Now type the following command:
loglog(x,y)
The command logspace is similar to linspace, however it creates a vector of 101 points
lograthmically equally distributed between 10-5 and 105.
The following commands are useful when plotting:
Graphing functions MATLAB command
Label the horizontal axis. xlabel('text')
Label the vertical axis. ylabel('text')
Attach a title to the plot. title('text')
Change the limits on the x and y axis.
axis([xmin xmax ymin
ymax])
"Keep plotting in the same window." hold on
Turn off the "keep-plotting-in-the-same-window-
command".
hold off
Note that all text must be put within ' '. The last two commands (hold on and hold off) are
best explained by trying them next time you plot.
Exercises
 Plot sin(x) on the interval [-pi,pi] using spacing 0.5, 0.1 and 0.01 between the points
where you will sample the function. (This will change the resolution). Experiment with
the hold on command.
 Attach labels to the axis of the previous plot and give a title to the graph.
 Plot 5 cos(x2+1) on [-2pi,2pi]. Note that the squaring operation will require you to use the
dot . in order for the squaring operation to act on each element individually. However,
the addition operation (+) automatically acts on elements individually.

More Related Content

What's hot

Introduction to MatLab programming
Introduction to MatLab programmingIntroduction to MatLab programming
Introduction to MatLab programmingDamian T. Gordon
 
Matlab Tutorial
Matlab TutorialMatlab Tutorial
Matlab Tutorial
Ahmad Siddiq
 
Matlab Overviiew
Matlab OverviiewMatlab Overviiew
Matlab Overviiew
Nazim Naeem
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
Khulna University
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
vikrammutneja1
 
Matlab commands
Matlab commandsMatlab commands
Matlab commands
Tarun Gehlot
 
All About MATLAB
All About MATLABAll About MATLAB
All About MATLAB
Multisoft Virtual Academy
 
Advanced MATLAB Tutorial for Engineers & Scientists
Advanced MATLAB Tutorial for Engineers & ScientistsAdvanced MATLAB Tutorial for Engineers & Scientists
Advanced MATLAB Tutorial for Engineers & Scientists
Ray Phan
 
Matlab 1(operations on_matrix)
Matlab 1(operations on_matrix)Matlab 1(operations on_matrix)
Matlab 1(operations on_matrix)
harman kaur
 
Matlab Workshop Presentation
Matlab Workshop PresentationMatlab Workshop Presentation
Matlab Workshop Presentation
Jairo Maldonado-Contreras
 
matlab Lesson 1
matlab Lesson 1matlab Lesson 1
matlab Lesson 1
Vinnu Vinay
 
Matlab
MatlabMatlab
Matlab-free course by Mohd Esa
Matlab-free course by Mohd EsaMatlab-free course by Mohd Esa
Matlab-free course by Mohd Esa
Mohd Esa
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
Dnyanesh Patil
 
MatLab Basic Tutorial On Plotting
MatLab Basic Tutorial On PlottingMatLab Basic Tutorial On Plotting
MatLab Basic Tutorial On Plotting
MOHDRAFIQ22
 
matlab
matlabmatlab
matlab
Farhan Ahmed
 
Matlab Manual
Matlab ManualMatlab Manual
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
Mukesh Kumar
 

What's hot (20)

Introduction to MatLab programming
Introduction to MatLab programmingIntroduction to MatLab programming
Introduction to MatLab programming
 
Matlab Tutorial
Matlab TutorialMatlab Tutorial
Matlab Tutorial
 
Matlab Overviiew
Matlab OverviiewMatlab Overviiew
Matlab Overviiew
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab commands
Matlab commandsMatlab commands
Matlab commands
 
All About MATLAB
All About MATLABAll About MATLAB
All About MATLAB
 
Advanced MATLAB Tutorial for Engineers & Scientists
Advanced MATLAB Tutorial for Engineers & ScientistsAdvanced MATLAB Tutorial for Engineers & Scientists
Advanced MATLAB Tutorial for Engineers & Scientists
 
MATLAB
MATLABMATLAB
MATLAB
 
Matlab 1(operations on_matrix)
Matlab 1(operations on_matrix)Matlab 1(operations on_matrix)
Matlab 1(operations on_matrix)
 
Matlab Workshop Presentation
Matlab Workshop PresentationMatlab Workshop Presentation
Matlab Workshop Presentation
 
matlab Lesson 1
matlab Lesson 1matlab Lesson 1
matlab Lesson 1
 
Matlab
MatlabMatlab
Matlab
 
Palm m3 chapter1b
Palm m3 chapter1bPalm m3 chapter1b
Palm m3 chapter1b
 
Matlab-free course by Mohd Esa
Matlab-free course by Mohd EsaMatlab-free course by Mohd Esa
Matlab-free course by Mohd Esa
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
MatLab Basic Tutorial On Plotting
MatLab Basic Tutorial On PlottingMatLab Basic Tutorial On Plotting
MatLab Basic Tutorial On Plotting
 
matlab
matlabmatlab
matlab
 
Matlab Manual
Matlab ManualMatlab Manual
Matlab Manual
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
 

Viewers also liked

Ramco systems - The Pursuit of Happiness
Ramco systems - The Pursuit of HappinessRamco systems - The Pursuit of Happiness
Ramco systems - The Pursuit of Happiness
Ramco Systems
 
Dsp mat lab.protected by Rajesh & Rahul Jha
Dsp mat lab.protected by Rajesh & Rahul Jha Dsp mat lab.protected by Rajesh & Rahul Jha
Dsp mat lab.protected by Rajesh & Rahul Jha
Infowiz Software Solution - India
 
Contents
ContentsContents
Contents
Jaspreet Kaur
 
PowerPoint Presentation
PowerPoint PresentationPowerPoint Presentation
PowerPoint PresentationVisualBee.com
 
Mid-South atlantic hftp meeting
Mid-South atlantic hftp meetingMid-South atlantic hftp meeting
Mid-South atlantic hftp meetingKevin Reilly
 
45p Tax Rate
45p Tax Rate45p Tax Rate
45p Tax Rate
Oliver Taylor
 
Zapatería colores (nadia el khitri)
Zapatería  colores (nadia el khitri)Zapatería  colores (nadia el khitri)
Zapatería colores (nadia el khitri)Nadiae94
 
25 03 2012 pagina encarte
25 03 2012 pagina encarte25 03 2012 pagina encarte
25 03 2012 pagina encarteDebora Teixeira
 
Presentatienerd in 7 stappen
Presentatienerd in 7 stappen Presentatienerd in 7 stappen
Presentatienerd in 7 stappen
LGND
 
Peptic Ulcer Disease Dr Shatdal
Peptic Ulcer Disease Dr ShatdalPeptic Ulcer Disease Dr Shatdal
Peptic Ulcer Disease Dr Shatdal
Shatdal Chaudhary
 
Reanimación neonatal Generalidades
Reanimación neonatal GeneralidadesReanimación neonatal Generalidades
Reanimación neonatal Generalidades
Hospital General de Pachuca
 
Peptic Ulcer Disease by Dr. Sookun Rajeev Kumar M.D
Peptic Ulcer Disease by Dr. Sookun Rajeev Kumar M.DPeptic Ulcer Disease by Dr. Sookun Rajeev Kumar M.D
Peptic Ulcer Disease by Dr. Sookun Rajeev Kumar M.D
Dr. Sookun Rajeev Kumar
 
A 2000-watt society - Energy use convergence for a just and sustainable worl...
A 2000-watt society - Energy use convergence  for a just and sustainable worl...A 2000-watt society - Energy use convergence  for a just and sustainable worl...
A 2000-watt society - Energy use convergence for a just and sustainable worl...
morosini1952
 
Síndrome de Aspiración de Meconio (SAM)
Síndrome de Aspiración de Meconio (SAM) Síndrome de Aspiración de Meconio (SAM)
Síndrome de Aspiración de Meconio (SAM)
Brian Vásquez
 
RECIÉN NACIDO: VALORACIÓN, CARACTERÍSTICAS, PERIODO DE TRANSICIÓN, SOMATOMETRÍA.
RECIÉN NACIDO: VALORACIÓN, CARACTERÍSTICAS, PERIODO DE TRANSICIÓN, SOMATOMETRÍA.RECIÉN NACIDO: VALORACIÓN, CARACTERÍSTICAS, PERIODO DE TRANSICIÓN, SOMATOMETRÍA.
RECIÉN NACIDO: VALORACIÓN, CARACTERÍSTICAS, PERIODO DE TRANSICIÓN, SOMATOMETRÍA.
Nancy Chavarría
 
Energetische Betriebsoptimierung - Monitoring
Energetische Betriebsoptimierung - MonitoringEnergetische Betriebsoptimierung - Monitoring
Energetische Betriebsoptimierung - Monitoring
Vorname Nachname
 

Viewers also liked (18)

Ramco systems - The Pursuit of Happiness
Ramco systems - The Pursuit of HappinessRamco systems - The Pursuit of Happiness
Ramco systems - The Pursuit of Happiness
 
Dsp mat lab.protected by Rajesh & Rahul Jha
Dsp mat lab.protected by Rajesh & Rahul Jha Dsp mat lab.protected by Rajesh & Rahul Jha
Dsp mat lab.protected by Rajesh & Rahul Jha
 
Contents
ContentsContents
Contents
 
PowerPoint Presentation
PowerPoint PresentationPowerPoint Presentation
PowerPoint Presentation
 
presentation
presentationpresentation
presentation
 
Mid-South atlantic hftp meeting
Mid-South atlantic hftp meetingMid-South atlantic hftp meeting
Mid-South atlantic hftp meeting
 
45p Tax Rate
45p Tax Rate45p Tax Rate
45p Tax Rate
 
Zapatería colores (nadia el khitri)
Zapatería  colores (nadia el khitri)Zapatería  colores (nadia el khitri)
Zapatería colores (nadia el khitri)
 
25 03 2012 pagina encarte
25 03 2012 pagina encarte25 03 2012 pagina encarte
25 03 2012 pagina encarte
 
Presentatienerd in 7 stappen
Presentatienerd in 7 stappen Presentatienerd in 7 stappen
Presentatienerd in 7 stappen
 
Certificate
CertificateCertificate
Certificate
 
Peptic Ulcer Disease Dr Shatdal
Peptic Ulcer Disease Dr ShatdalPeptic Ulcer Disease Dr Shatdal
Peptic Ulcer Disease Dr Shatdal
 
Reanimación neonatal Generalidades
Reanimación neonatal GeneralidadesReanimación neonatal Generalidades
Reanimación neonatal Generalidades
 
Peptic Ulcer Disease by Dr. Sookun Rajeev Kumar M.D
Peptic Ulcer Disease by Dr. Sookun Rajeev Kumar M.DPeptic Ulcer Disease by Dr. Sookun Rajeev Kumar M.D
Peptic Ulcer Disease by Dr. Sookun Rajeev Kumar M.D
 
A 2000-watt society - Energy use convergence for a just and sustainable worl...
A 2000-watt society - Energy use convergence  for a just and sustainable worl...A 2000-watt society - Energy use convergence  for a just and sustainable worl...
A 2000-watt society - Energy use convergence for a just and sustainable worl...
 
Síndrome de Aspiración de Meconio (SAM)
Síndrome de Aspiración de Meconio (SAM) Síndrome de Aspiración de Meconio (SAM)
Síndrome de Aspiración de Meconio (SAM)
 
RECIÉN NACIDO: VALORACIÓN, CARACTERÍSTICAS, PERIODO DE TRANSICIÓN, SOMATOMETRÍA.
RECIÉN NACIDO: VALORACIÓN, CARACTERÍSTICAS, PERIODO DE TRANSICIÓN, SOMATOMETRÍA.RECIÉN NACIDO: VALORACIÓN, CARACTERÍSTICAS, PERIODO DE TRANSICIÓN, SOMATOMETRÍA.
RECIÉN NACIDO: VALORACIÓN, CARACTERÍSTICAS, PERIODO DE TRANSICIÓN, SOMATOMETRÍA.
 
Energetische Betriebsoptimierung - Monitoring
Energetische Betriebsoptimierung - MonitoringEnergetische Betriebsoptimierung - Monitoring
Energetische Betriebsoptimierung - Monitoring
 

Similar to Introduction to matlab

Mmc manual
Mmc manualMmc manual
Mmc manual
Urvi Surat
 
interfacing matlab with embedded systems
interfacing matlab with embedded systemsinterfacing matlab with embedded systems
interfacing matlab with embedded systems
Raghav Shetty
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
MahuaPal6
 
Matlab guide
Matlab guideMatlab guide
Matlab guide
aibad ahmed
 
Basic matlab for beginners
Basic matlab for beginnersBasic matlab for beginners
Basic matlab for beginners
Kwabena Owusu-Agyemang
 
Maple
MapleMaple
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
ssuser772830
 
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docxMATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
andreecapon
 
Brief Introduction to Matlab
Brief  Introduction to MatlabBrief  Introduction to Matlab
Brief Introduction to Matlab
Tariq kanher
 
1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx
MOHAMMAD SAYDUL ALAM
 
MATLAB guide
MATLAB guideMATLAB guide
MATLAB guide
Prerna Rathore
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Kurmendra Singh
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
amanabr
 

Similar to Introduction to matlab (20)

Mmc manual
Mmc manualMmc manual
Mmc manual
 
interfacing matlab with embedded systems
interfacing matlab with embedded systemsinterfacing matlab with embedded systems
interfacing matlab with embedded systems
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
 
Matlab tut2
Matlab tut2Matlab tut2
Matlab tut2
 
Matlab guide
Matlab guideMatlab guide
Matlab guide
 
Matlab summary
Matlab summaryMatlab summary
Matlab summary
 
Basic matlab for beginners
Basic matlab for beginnersBasic matlab for beginners
Basic matlab for beginners
 
Matlab booklet
Matlab bookletMatlab booklet
Matlab booklet
 
Maple
MapleMaple
Maple
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docxMATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
 
Brief Introduction to Matlab
Brief  Introduction to MatlabBrief  Introduction to Matlab
Brief Introduction to Matlab
 
1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx
 
MATLAB guide
MATLAB guideMATLAB guide
MATLAB guide
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Matlab1
Matlab1Matlab1
Matlab1
 

Introduction to matlab

  • 1. Introduction to MATLAB Originally created by Kristian Sandberg Department of Applied Mathematics University of Colorado Updated for compatibility with Release 13 by Grady Wright Department of Mathematics University of Utah Goal The goal of this tutorial is to give a brief introduction to the mathematical software MATLAB. After completing the worksheet you should know how to start MATLAB, how to use the elementary functions in MATLAB and how to use MATLAB to plot functions. What is MATLAB? MATLAB is widely used in all areas of applied mathematics, in education and research at universities, and in the industry. MATLAB stands for MATrix LABoratory and the software is built up around vectors and matrices. This makes the software particularly useful for linear algebra but MATLAB is also a great tool for solving algebraic and differential equations and for numerical integration. MATLAB has powerful graphic tools and can produce nice pictures in both 2D and 3D. It is also a programming language, and is one of the easiest programming languages for writing mathematical programs. MATLAB also has some tool boxes useful for signal processing, image processing, optimization, etc. How to start MATLAB Mac: Double-click on the icon for MATLAB. PC: Choose the submenu "Programs" from the "Start" menu. From the "Programs" menu, open the "MATLAB" submenu. From the "MATLAB" submenu, choose "MATLAB". Unix: At the prompt, type matlab. You can quit MATLAB by typing exit in the command window. The MATLAB environment Note: From now on an instruction to press a certain key will be denoted by < >, e.g., pressing the enter key will be denoted as <enter>. Commands that should be typed at the prompt, will be written in courier font.
  • 2. The MATLAB environment (on most computer systems) consists of menus, buttons and a writing area similar to an ordinary word processor. There are plenty of help functions that you are encouraged to use. The writing area that you will see when you start MATLAB, is called the command window. In this window you give the commands to MATLAB. For example, when you want to run a program you have written for MATLAB you start the program in the command window by typing its name at the prompt. The command window is also useful if you just want to use MATLAB as a scientific calculator or as a graphing tool. If you write longer programs, you will find it more convenient to write the program code in a separate window, and then run it in the command window (discussed in Intro to programming). In the command window you will see a prompt that looks like >> . You type your commands immediately after this prompt. Once you have typed the command you wish MATLAB to perform, press <enter>. If you want to interupt a command that MATLAB is running, type <ctrl> + < c>. The commands you type in the command window are stored by MATLAB and can be viewed in the Command History window. To repeat a command you have already used, you can simply double-click on the command in the history window, or use the <up arrow> at the command prompt to iterate through the commands you have used until you reach the command you desire to repeat. Useful functions and operations in MATLAB Using MATLAB as a calculator is easy. Example: Compute 5 sin(2.53-pi)+1/75. In MATLAB this is done by simply typing 5*sin(2.5^(3-pi))+1/75 at the prompt. Be careful with parantheses and don't forget to type * whenever you multiply! Note that MATLAB is case sensitive. This means that MATLAB knows a difference between letters written as lower and upper case letters. For example, MATLAB will understand sin(2) but will not understand Sin(2). Here is a table of useful operations, functions and constants in MATLAB. Operation, function or constant MATLAB command + (addition) + - (subtraction) - × (multiplication) * / (division) / |x| (absolute value of x) abs(x)
  • 3. square root of x sqrt(x) ex exp(x) ln x (natural log) log(x) log10 x (base 10 log) log10(x) sin x sin(x) cos x cos(x) tan x tan(x) cot x cot(x) arcsin x asin(x) arccos x acos(x) arctan x atan(x) arccot x acot(x) n! (n factorial) gamma(n+1) e (2.71828...) exp(1)  (3.14159265...) pi i (imaginary unit, sqrt(-1)) i Exercises Compute the following expressions using MATLAB:  3cos(pi)  1+1+1/2+1/6+1/24-e  ln (1000+2pi-2)  e i pi  The number of combinations in which 12 persons can stand in line. (Hint: Use factorials.) Obtaining Help on MATLAB commands To obtain help on any of the MATLAB commands, you simply need to type help <command> at the command prompt. For example, to obtain help on the gamma function, we type at the command prompt: help gamma Try this now. You may also get help about commands using the "Help Desk", which can be accessed by selecting the MATLAB Help option under the Help menu.
  • 4. Note that the description MATLAB returns about the command you requested help on contains the command name in ALL CAPS. This does not mean that you use this command by typing it in ALL CAPS. In MATLAB, you almost always use all lower case letters when using a command. Variables in MATLAB We can easily define our own variables in MATLAB. Let's say we need to use the value of 3.5sin(2.9) repeatedly. Instead of typing 3.5*sin(2.9)over and over again, we can denote this variable as x by typing the following: x=3.5*sin(2.9) (Please try this in MATLAB.) Now type x+1 and observe what happens. Note that we did not need to declare x as a variable that is supposed to hold a floating point number as we would need to do in most programming languages. Often, we may not want to have the result of a calculation printed-out to the command window. To supress this output, we put a semi-colon at the end of the command; MATLAB still performs the command in "the background". If you defined x as above, now type y=2*x; y and observe what happened. In many cases we want to know what variables we have declared. We can do this by typing whos. Alternatively, we can view the values by openning the "Workspace" window. This is done by selecting the Workspace option from the View menu. If you want to erase all variables from the MATLAB memory, type clear. To erase a specific variable, say x, type clear x. To clear two specific variables, say x and y, type clear x y, that is separate the different variables with a space. Variables can also be cleared by selecting them in the Workspace window and selecting the delete option. Vectors and matrices in MATLAB We create a vector in MATLAB by putting the elements within [] brackets. Example: x=[ 1 2 3 4 5 6 7 8 9 10] We can also create this vector by typing x=1:10. The vector (1 1.1 1.2 1.3 1.4 1.5) can be created by typing x=[ 1 1.1 1.2 1.3 1.4 1.5 ] or by typing x=1:0.1:1.5.
  • 5. Matrices can be created according to the following example. The matrix A= is created by typing A=[1 2 3 ; 4 5 6; 7 8 9], i.e., rows are separated with semi-colons. If we want to use a specific element in a vector or a matrix, study the following example: Example: x=[10 20 30] A=[ 1 2 3 ; 4 5 6 ; 7 8 9] x(2) A(3,1) Here we extracted the second element of the vector by typing the variable and the position within parantheses. The same principle holds for matrices; the first number specifies the row of the matrix, and the second number specifies the column of the matrix. Note that in MATLAB the first index of a vector or matrix starts at 1, not 0 as is common with other programming languages. If the matrices (or vectors which are special cases of a matrices) are of the same dimensions then matrix addition, matrix subtraction and scalar multiplication works just like we are used to. Example: Type x=[1 2 3] y =[4 5 6] a=2 x+y x-y a*x and observe what happens. If want to apply an operation such as squaring each element in a matrix we have to use a dot . before the operation we wish to apply. Type the following commands in MATLAB.
  • 6. x=1:10 x.^2 A=[1 2 3 ; 4 5 6 ; 7 8 9 ] A.^2 A^2 and observe the result. The dot allows us to do operations elementwise. All built-in functions such as sin, cos, exp and so on automatically act elementwise on a matrix. Type y=[0 1/4 1/2 3/4 1] y=pi*y sin(y) and observe the result. How to plot with MATLAB There are different ways of plotting in MATLAB. The following two techniques, illustrated by examples, are probably the most useful ones. Example 1: Plot sin(x2) on the interval [-5,5]. To do this, type the following: x=-5:0.01:5; y=sin(x.^2); plot(x,y) and observe what happens. Example 2: Plot exp(sin(x)) on the interval [-,]. To do this, type the following: x=linspace(-pi,pi,101); y=exp(sin(x)); plot(x,y) and observe what happens. The command linspace creates a vector of 101 equally spaced values between - and  (inclusive).
  • 7. Ocassionally, we need to plot values that vary quite differently in magnitude. In this case, the regular plot command fails to give us an adequate graphical picture of our data. Instead, we need a command that plots values on a log scale. MATLAB has 3 such commands: loglog,semilogx, and semilogy. Use the help command to see a description of each function. As an example of where we may want to use one of these plotting routines, consider the following problem: Example 3: Plot x5/2 for x = 10-5 to 105. To do this, type the following: x=logspace(-5,5,101); y=x.^(5/2); plot(x,y) and observe what happens. Now type the following command: loglog(x,y) The command logspace is similar to linspace, however it creates a vector of 101 points lograthmically equally distributed between 10-5 and 105. The following commands are useful when plotting: Graphing functions MATLAB command Label the horizontal axis. xlabel('text') Label the vertical axis. ylabel('text') Attach a title to the plot. title('text') Change the limits on the x and y axis. axis([xmin xmax ymin ymax]) "Keep plotting in the same window." hold on Turn off the "keep-plotting-in-the-same-window- command". hold off Note that all text must be put within ' '. The last two commands (hold on and hold off) are best explained by trying them next time you plot. Exercises  Plot sin(x) on the interval [-pi,pi] using spacing 0.5, 0.1 and 0.01 between the points where you will sample the function. (This will change the resolution). Experiment with the hold on command.
  • 8.  Attach labels to the axis of the previous plot and give a title to the graph.  Plot 5 cos(x2+1) on [-2pi,2pi]. Note that the squaring operation will require you to use the dot . in order for the squaring operation to act on each element individually. However, the addition operation (+) automatically acts on elements individually.