Introduction to MATLAB Math 375 Getting started Arithmetics Matrices Plotting Functions Program Control Introduction to MATLAB Math 375 Natalia Vladimirova (many ideas, examples, and excersises are borrowed from Profs. Monika Nitsche, Richard Allen, and Stephen Lau) January 24, 2010
40
Embed
Introduction to MATLAB - University of New Mexiconvladimi/math375/matlab.pdf · Click on the "Start" menu button Click on the "MATLAB" menu entry ... double click on a variable to
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
Program Control
Introduction to MATLAB
Math 375Natalia Vladimirova
(many ideas, examples, and excersises are borrowed fromProfs. Monika Nitsche, Richard Allen, and Stephen Lau)
January 24, 2010
Introduction toMATLAB
Math 375
Getting started
Starting MATLAB
Desktop Tools
Getting Help
Saving your work
Arithmetics
Matrices
Plotting
Functions
Program Control
Starting MATLABI Under windows
Click on the ”Start” menu buttonClick on the ”MATLAB” menu entry
I Under LinuxUse SSH to log onto linux.unm.eduType matlab
Introduction toMATLAB
Math 375
Getting started
Starting MATLAB
Desktop Tools
Getting Help
Saving your work
Arithmetics
Matrices
Plotting
Functions
Program Control
Desktop ToolsI Command Window
type commands
I Workspaceview program variablesdouble click on a variable to see it in the Array Editor
I Command Historyview past commands
I Current Directoryview and select files in the current directorythe current directory can be changed in the toolbar
I To switch to the default windows arrangement, go to menuDesktop > Desktop Layout > Default
Introduction toMATLAB
Math 375
Getting started
Starting MATLAB
Desktop Tools
Getting Help
Saving your work
Arithmetics
Matrices
Plotting
Functions
Program Control
Getting HelpI Using the Help Browser
I From command window
>> help
>> help plot
I Running demos
>> demos
>> help demos
I On the webhttp://www.mathworks.com
Introduction toMATLAB
Math 375
Getting started
Starting MATLAB
Desktop Tools
Getting Help
Saving your work
Arithmetics
Matrices
Plotting
Functions
Program Control
Saving your workI in class, create your directory (folder) in T: drive
I MATLAB files reside on the current directory or the searchpath
>> addpath T:\myfolder
>> addpath ~/matlab
I you can save a whole session using
>> diary "diary_Jan23.txt"
>> diary off
>> diary on
I bring your flash card (floppy, CD-RW) to save class work
I or upload your files to your UNM storage (?)
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Variables
Build-in constants
Arithmetic operators
Logical operators
Math functions
Scripts
Matrices
Plotting
Functions
Program Control
VariablesI creating a variable (MATLAB is case sensitive);
I Save your figure as *.fig - this way you can modify it later.
I Save PDF on letter-size paper. Here “gcf” is the handle tocurrent figure (“get current figure”). The plot position on thepaper is given as the coordinates of upper-left and lower-rightcorners
>> set(gcf, ’papersize’, [8.5, 11], ...
’paperposition’, [1, 1, 6, 4])
>> saveas(gcf,’myplot.pdf’,’pdf’)
I If figure to be inserted into a document, use paper size sameas plot size
>> set(gcf, ’papersize’, [6, 4], ...
’paperposition’, [0, 0, 6, 4])
>> saveas(gcf,’myplot.pdf’,’pdf’)
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Simple plot
Label you plots!
Saving plots
Markers
Multiple Plots
In class exercise
Functions
Program Control
Marker options (type help plot to remind)
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star (none) no line
y yellow s square
k black d diamond
w white v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Simple plot
Label you plots!
Saving plots
Markers
Multiple Plots
In class exercise
Functions
Program Control
Multiple graphs, panels, and figuresI Multiple graphs on the same plot (also see help hold)
>> x = linspace(0, 2*pi, 100);
>> y1 = cos(3*t) .* exp(-0.5*t);
>> y2 = sin(3*t) .* exp(-0.5*t);
>> plot(t,y1,’x’, t,y2, ’*’)
I To open new figure (new window)
>> figure
>> figure(1) %make figure 1 current figure
I To divide figure to panels
>> subplot(2,2,1)
>> plot(t,y1)
>> subplot(2,2,2)
>> plot(t,y2)
>> subplot(2,2,3)
>> plot(y1,y2)
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Simple plot
Label you plots!
Saving plots
Markers
Multiple Plots
In class exercise
Functions
Program Control
In class exercise
By plotting y(t) below with different values of parameter a find aat which y(t) passes through given “experimental” points as closeas possible
y(t) = e−t2 sin(at)
t = 0.1 0.5 0.9 1.3 1.7 ...
2.1 2.5 2.9 3.3 3.7
y = 0.648 -0.445 0.287 -0.167 0.078 ...
-0.015 -0.028 0.056 -0.072 0.079
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
User defined ...
... more
... more
Function handles
Program Control
User defined functionsI Unlike scripts, functions can take arguments and return values
I Like scripts, MATLAB functions reside in M-files (*.m)
I Name of the file = name of the function
I Example of function file mycomplex.m
mycomplex.m
function z = mycomplex(x,y)
z = x + i*y;
end
here x and y are arguments, z is returned value,and mycomplex is the name of the function
I Call it from command line or from another function
>> c = mycomplex(a,b)
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
User defined ...
... more
... more
Function handles
Program Control
User defined functions (cont.)I Functions can take matrices as arguments
I Functions can return multiple values
I You can put several functions in a single M-file.
I Example: function file myplot.m
myplot.mfunction myplot
[x,y] = mydata(n);
plot(x,y);
end
function [x,y] = mydata(n)
x = linspace(0, 2*pi, n);
y = sin(x);
end
I Can we call mydata(n) from command line?
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
User defined ...
... more
... more
Function handles
Program Control
User defined functions (cont.)I Example: function file mycart2pol.m
mycart2pol.m
function[ radius, theta ] = mycart2pol(x, y)
% convert cartesian coordinares (x, y)
% to polar coordinates (r, theta)
theta = atan2(y, x);
radius = sqrt(x.^2 + y.^2);
end
I What happens when you call mycart2pol as following?
>> mycart2pol(1,1)
>> r = mycart2pol(1,1)
>> [r th] = mycart2pol(1,1)
>> [r th] = mycart2pol([-1 -2 -3], [0 0 0])
>> help mycart2pol
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
User defined ...
... more
... more
Function handles
Program Control
Function handlesI There are a number of useful MATLAB functions which take
function handle as an argumentI Example: to numerically evaluate integral∫ 2
1
x3dx =1
4
(24 − 14
)= 3.75
using MATLAB function quad we first create file cube.m
cube.mfunction y = cube(x)
y = x.^3;
end
I and then pass the function handle (@cube) and integrationlimits (1,2) to quad
>> quad(@cube, 1, 2)
I or create inline function, defined by the string
>> f = inline(’x.^3’);
>> quad(f, 1, 2)
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
Program Control
For loop
For loop: examples
For loop: examples
While loop
If statement
If-else statement
If-else example
Other statements
Simple text I/O
For loopI The for loop executes a statement or group of statements a
predetermined number of times.
for x = x1 : ∆x : xnstatement
end
I The increment ∆x can be omitted; default ∆x = 1
for x = x1 : xnstatement
end
I The index of a for loop can be an array.
v=v1 : ∆v : vnfor x = v
statementend
I For loops can be nested
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
Program Control
For loop
For loop: examples
For loop: examples
While loop
If statement
If-else statement
If-else example
Other statements
Simple text I/O
For loop: examples
>> format compact
>> for n = 1:5
disp(n)
end
>> for n = 0.5:0.1:0.8
disp(n)
end
>> v = [2, 4, 8, 16];
>> for n = v
disp(n)
end
>> for j = 1:3
for i = 1:3
A(i,j) = i+j;
end
end
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
Program Control
For loop
For loop: examples
For loop: examples
While loop
If statement
If-else statement
If-else example
Other statements
Simple text I/O
For loop: examples
Create vector [1 2 3 4 5] in a “classical” way
>> v = zeros(1,5) % allocate space
>> for i=1:5 % cycle through the elements
v(i)=i % assign value to each element
end
Note: allocation is optional (but it makes the code run faster).Try the following:
>> clear v
>> for i=1:5
v(i)=i
end
>> v = zeros(1,5)
>> a = v(8)
>> v(8) = 8
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
Program Control
For loop
For loop: examples
For loop: examples
While loop
If statement
If-else statement
If-else example
Other statements
Simple text I/O
While loop
The while loop executes a statement or group of statementsrepeatedly as long as the controlling expression is true
while conditionstatement
end
>> x=1;
>> while x > 0.01
x = x/2
end
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
Program Control
For loop
For loop: examples
For loop: examples
While loop
If statement
If-else statement
If-else example
Other statements
Simple text I/O
If statement
If evaluates a logical expression and executes a group ofstatements based on the value of the expression.
if conditionstatement
end
Example: find the maximum element in an array:
>> v=rand(1,6)
>> vmax = -1;
>> for i=1:length(v)
if v(i) > vmax
vmax = v(i);
end
end
>> disp(vmax)
But, of coarse, it is easier just to do
>> vmax = max(max(v))
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
Program Control
For loop
For loop: examples
For loop: examples
While loop
If statement
If-else statement
If-else example
Other statements
Simple text I/O
If-else statement
if-else can take care for both branches of the fork...
if condition1statement1
elsestatement2
end
... or multiple branches
if condition1statement1
elseif condition2statement2
elseif condition3statement3
elsestatement4
end
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
Program Control
For loop
For loop: examples
For loop: examples
While loop
If statement
If-else statement
If-else example
Other statements
Simple text I/O
If-else example
Script rps.m simulates a rock-paper-scissors player
rpm.s
% simulate a rock-paper-scissors player
x = rand(1) % get random number between 0 to 1
x = x*3 % rescale x so that 0 < x < 3
if x<1
disp(’rock!’)
elseif x<2
disp(’paper!’)
else
disp(’scissors!’)
end
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
Program Control
For loop
For loop: examples
For loop: examples
While loop
If statement
If-else statement
If-else example
Other statements
Simple text I/O
Other program control statements
continue passes control to the next iteration of the loop
break terminates the execution of a loop
return exits the currently running function
switch executes statements based on the value of a variable orexpression
try, catch error control statements
Note: there is no goto statement in MATLAB
Introduction toMATLAB
Math 375
Getting started
Arithmetics
Matrices
Plotting
Functions
Program Control
For loop
For loop: examples
For loop: examples
While loop
If statement
If-else statement
If-else example
Other statements
Simple text I/O
Simple text input and outputI C-style output to the screen
>> fprintf(’square root of %d is %6.3f\n’, 3, sqrt(3))