Matlab Basics - Uppsala University · • An object oriented programming language that can be...
Transcript of Matlab Basics - Uppsala University · • An object oriented programming language that can be...
Matlab Basics
Richard Wait
September 3, 2007
Contents
• What is MATLAB?
• Workspace
• MATLAB environment
• Variables in MATLAB
• Functions in MATLAB
• Examples
– Graphics
– Computation
– Pictures
– GUI
Introduction
What is MATLAB?
• Developed by MathWorks Inchttp://www.mathworks.com
• First version ready by end 1970’s
• Matrix Laboratory for
1
– Numerical Computation
– Graphics
– Programming
• A simple environment for quick test of ideas and study of results
• Now, an advanced interactive software environment for computationand visualisation, runs under UNIX/Linux, windows or Macintosh
• Many predefined functions with possibility of user defined functions
• An object oriented programming language that can be linked to C++,Java and Fortran
• Over 25 specialised toolboxes
– Signal Processing
– Statistics
– Symbolic Mathematics
– Financial Mathematics
MATLAB Environment
• MATLAB Desktop has several tools, e.g. Command Window
The MATLAB Desktop
2
• MATLAB steered from the command window
• Commands follow the >>-prompt and finished with <ret>
• Example:>> 42 + 19
>> ans =
61
• Note that a semicolon ; supresses the output
• Example:>> a = 75
a =
75
>> b = 34;
>> a + b
ans =
109
MATLAB Environment: Help
• Via the help menu or the command >> helpbrowser
• Via the command >> help as in
3
>> help exit
EXIT exit from MATLAB
Variables in MATLAB
A variable in MATLAB:
• always has a name
• contains a data of a particular type (real, text)
• can be a matrix without the need for any special declaration
• is displayed in the workspace window
• cam be listed using who or whos
• can be predefined e.g. pi, ans
• can be displyed in different formats
>> format short
>> pi
3.1416
>> format long
>> pi
3.14159265358979
The value is unchanged only the output changes
Matrices: Concepts
• Matrices are the basic type type
>> vrow = [1, 2, 4, 5]
vrow =
4
1 2 4 5
>> size(vrow)
ans =
1 4
>> vcol = [1; 2; 4; 5]
vcol =
1
2
4
5
>> size(vcol)
ans =
4 1
>> length(vcol)
ans =
4
• Defining a matrix
>> A = [1 2; 4 5]
A =
1 2
4 5
>> A = [1 3
7 8]
A =
1 3
7 8
>> A’
ans =
1 7
3 8
• two uses for ; and ’ means transpose
• Addition >> C=A+B
• Multiplication >> C=A*B
5
• Division >> C=A/B or >> C=A\B
– >> C=A\B solves AC = B
– >> C=A/B solves CB = A
• Dimensions must be compatible, otherwise error message
• Starting from A =
(
1 37 8
)
construct A =
1 37 82 1
• Either >> A=[A ; 2 1];
• Or
>> k = [2 1];
>> A = [A; k];
• A(i,j) is the element in row i column j
• A(:,j) is the whole of column j
• A(i,:) is the whole of row i
• A(i:j,k:l) is the submatrix, rows i − j and columns k − l
• A matrix with all elements unity >> B=ones(3,5);
– >> B=ones(3); defines a 3 × 3
– >> B=ones(3,1); defines a column vector of length 3
• A matrix with all elements zero (the null matrix) >> C=zeros(2,4);
– >> C=zeros(3); defines a 3 × 3
– >> C=zeros(3,1); defines a column vector of length 3
• The unit (identity) matrix
6
>> A = eye(2)
A =
1 0
0 1
•>> B = [1 7; 5 3];
>> B∧2ans =
36 28
20 44
>> B.∧2ans =
1 49
25 9
Functions and Operations
• min(x) gives the minimum value in x, columnwise if x is a matrix
• max(x) maximum value in the same sense
• sum(x) sum of elements in x
• mean(x)
• std(x) standard deviation
• real(x) real parts
• imag(x) imaginary parts
• Using the colon notation
>> v1 = 0:5
v1 =
0 1 2 3 4 5
7
>> V2 = 0.0:0.05:2.;
>> length(v2)
ans =
41
• Using the linspace
>> v3 = linspace(0.0, 2.0, 41);
>> max( v2 - v3 )
ans =
2.2204e-016
• Note rounding error as MATLAB does not store real numbers exactly
Saving and Loading code
• A command file (script file) is a set of commands that would otherwisehave to be input interactively in the command window
• All the commands in the file can be executed and the results appearsin the command window
• All files must be named with the suffix m such as myfile.m
• To execute write the name in the command window (without suffix .m)thus
>> myfile
Programming in MATLAB
M-Files
• MATLAB instructions can be stored
• M-files
– Script files
– Functions can be defined in MATLAB
8
Operations
• relational operators
– < less than
– <= less than or equal to
– == equal to
– ∼= not equal to
• MATLAB logical operations
– A&B A and B
– A|B A or B
– ∼A not A
• Examples
– (x==1) & (y<2)
– abs(x-pi) > 1e-14
Conditional Statement
• If - End
x = input(’Give a number x:’);
if x>0
disp(’x greater than zero!’)
end
If - Else
• if - else
if <logical expression>
statements
else
statements
end
9
• elseif
if <logical expression>
statements
elseif <logical expression>
statements
else
statements
end
Iteration
• for - end
x = input(’Give a number x:’);
for i = 1:10
x = (x+1/x)/2;
end
For - End
• Standard form
for variable = <expression>
statements
end
• one-line
for var = <exp>, ..., end
10
Example
•r = []; s = [];
for x=-2.0:0.25:-0.75
y = 1+1/x;
r = [r x];
s = [s y];
end
[r; s]’
Iteration
• while - end
x = [];
a = 1;
while a > 0
x = [x a];
a = input (’Enter value; ’);
end
while - end
• Standard form
while <logical expression>
statements
end
• one-line
while <logical exp>, ..., end
Functions
• Standard functions sin(x), etc.
11
• User defined functions
function[x, y] = myfunc(x0,x1,n)
% My first function
x = linspace(x0, x1, n);
y = cos(x) + sin(x);
plot(x,y)
• Save as myfunc.m
Using Functions
• Execute as
xstart = 0; xend = pi; n = 100;
[x, y] = myfunc(xstart, xend, n);
Optional arguments
• Using varagin
function[x, y] = myfunc(x0,x1,...
n, varargin)
x = linspace(x0, x1, n);
y = cos(x) + sin(x);
plot(x,y,varargin{:})
• Execute as
[x, y] = myfunc(xstart, xend, n);
• Or execute as
[x, y] = myfunc(xstart, xend, ...
n, ’color’,[.5 .7 .3], ...
’linestyle’,’:’);
Global Parameters
function[y] = myfunc(x)
global w
z = cos(x) + w;
y = z + sin(x);
12
• Input parameters - x
• Output parameters - y
• Local variables - z
• Global variables - w
• Execute as
global w;
x = 1; w = 2;
y = myfunc(x);
Plotting a function
x=linspace(0,1);
y=x.*sin(x);
plot(x,y)
Multiple plots
x=linspace(0,2*pi,10);
y=cos(x).*sin(x);
plot(x,y)
hold on
y=sin(x); plot(x,y)
13
Simple plots
ezplot(’sin(x)’,[0,10])
0 1 2 3 4 5 6 7 8 9 10
−1
−0.5
0
0.5
1
x
sin(x)
Data Plots
x=[10,15,5,3,7,20];
stem(x)
title(’Parking’)
xlabel(’CarType’)
ylabel(’No of Cars’)
print -deps matplot3
14
1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 60
2
4
6
8
10
12
14
16
18
20Parking
CarType
No
of C
ars
Data Plots
pie(x,{’blue’,’red’,’black’,...
’yellow’,’white’,’other’})
title(’Parking’)
print -deps matplot4
blue
red
black yellow
white
other
Parking
ld=rand(1,100)/2+1.6;
hist(ld)
title(’heights’)
15
1.6 1.65 1.7 1.75 1.8 1.85 1.9 1.95 2 2.05 2.10
5
10
15heights
Scatter Plots
ld=rand(1,10)/2+1.6;
y=1:10;
plot(y,ld,’ro’)
1 2 3 4 5 6 7 8 9 101.65
1.7
1.75
1.8
1.85
1.9
1.95
2
2.05
2.1
Plots in 3D
t=0:0.01:10; x=sin(t);
y=cos(t); z=exp(t/10);
plot3(x,y,z)
xlabel(’x’), ylabel(’y’),
zlabel(’z’)
grid
16
−1
−0.5
0
0.5
1
−1
−0.5
0
0.5
11
1.2
1.4
1.6
1.8
2
2.2
2.4
2.6
2.8
xy
z
Simple Surface Plots
ezsurf(’x*exp(-x^2-y^2)’)
−3−2
−10
12
3
−3
−2
−1
0
1
2
3−0.5
0
0.5
x
x exp(−x2−y2)
y
Graphics Output
• The Graph appears as a separate window
17
Saving graphics
print stuff1
• print creates a file stuff1.ps
• black and white postscript is the default
print -d epsc stuff2
• print creates a file stuff2.eps
• other alternatives include encapsulated postscript eps with colour epsc
18
0 5 10 15 20 25 30 35 40 45
15
20
25
30
35
40
45
50
exam marks
hom
ewor
k m
arks
Least squares lines to fit observed data
X=10.6069+0.41823*YY=16.9983+0.51059*X
19
20