Post on 27-Jun-2020
transcript
Introduction to MATLAB®
Thayer School of Engineering
January 17, 2004
Eric Hansen 2003
adapted from
AgendaSession 1: 9:00 - 10:00
What is Matlab?
Getting started
Session 2: 10:00 - 11:00
Computation
Session 3: 11:00 - 12:00
Graphics
Scientific computing today
Traditional programming languages:
Basic, Pascal, Fortran, C, C++, Java
Numeric/graphics: Matlab, IDL, Octave
Symbolic: Maple, Mathematica, MathCad
Dataflow: LabView, VEE, Simulink, OpenDX, AVS
What is Matlab?MATrix LABoratory
Accurate numerics
Flexible graphics
Interactive, programmable
Platform-independent
Runs on Unix/Linux, Windows, and Mac computers
Extensible
Add-on toolboxes for particular applications
User-defined functions (M-files)
What is Matlab?
User interfaceCore numerics and graphics
Numerical and graphical M-files
User-written functions in C or Fortran
Special-purpose toolboxes
User-written M-files
How to get helpPrinted manuals (if you own a copy of the software) or
Books — my favorite is Mastering MATLAB by Hanselman and Littlefield (Prentice-Hall)
help command (information on particular functions)
or
doc command (all MATLAB documentation)
On the Internet: � http://www.mathworks.com/support� http://www.mathworks.com/products/
education/
student_version/tutorials/index.shtml
Newsgroup: comp.soft-sys.matlab
Where is Matlab at Thayer?
Your own computer
Student Edition: $99
Extend Dartmouth site license?
Windows computers in Room 222 (analog lab)
Linux and Windows computers in Rooms 225, 227
~50 licenses
Getting startedLog in to a computer — your username and password
will work with both Linux and Windows.
Start Matlab — Look in “Start” menu for Windows or the “RedHat>Thayer School” menu for Linux.
Matlab Graphical User Interface
Using Matlab as a calculator
Basic datatype is double-precision array
Scalar: x = 2
Row vector: x = [1, 2, 3]
Column vector: x = [1; 2; 3]
Matrix: x = [1, 2, 3; 4, 5, 6]
Arrays know their dimensions. Checking is automatic.
Using Matlab as a calculator
Assignment statements>> x=3 >> is the Matlab prompt
x =
3
>> x=3; Semicolon suppresses output
>> x+2
ans =
5 If no LHS, result is put into variable “ans”
>> ans*3
ans =
15 ans can be used by name
Using Matlab as a calculator
How big is my vector or matrix? length() and size()>> x=[1, 2, 3]; >> length(x)ans =
3>> size(x)ans =
1 3 One row, three columns>> y=[1, 2, 3; 4, 5, 6];>> size(y)ans =
2 3 Two rows, three columns>> length(y)ans =
3 length() returns the largest dimension
Using Matlab as a calculator
Basic arithmetic: +, -, *, /, ^
Scalars and vectors>> x=[1, 2, 3]
x =
1 2 3
>> x+2
ans =
3 4 5 Adds scalar to each element of array
>> 3*x
ans =
3 6 9 Multiplies each element of array by scalar
Using Matlab as a calculatorVectors and vectors — use +, -, .*, ./, .^ for ordinary arithmetic
>> x=[1, 2, 3];>> y=[4 5 6]; You can leave the commas out>> y-xans = Subtracts element-by-element
3 3 3 (vectors must be the same size!)>> x.*yans = 4 10 18 (x*y is a matrix operation)>> x.^2ans= 1 4 9>> y.^xans=
4 25 216
Using Matlab as a calculator
Grouping operations>> x=[1, 2, 3];
>> y=[4, 5, 6];
>> 2*(x+1)
ans =
4 6 8
>> 2*(x-y) + 1
ans =
-3 -3 -3
Using Matlab as a calculatorVectors and vectors — use * for dot (inner) product
>> x=[1, 2, 3];>> y=[4 5 6];>> x*y
??? Error using ==> *Inner matrix dimensions must agree.
>> y = [4; 5; 6]y = 4 5 6>> x*yans= 32
Using Matlab as a calculator
Matrices and vectors >> A=[1 2; 3 4]; 2x2 matrix
>> x=[1 2]; 2 element row vector
>> y=[2; 3]; 2 element column vector
>> x*A
ans = row * matrix = row
7 10
>> A*yans = matrix * column = column
818
Time for labFind a machine and log in
Start Matlab
Work through the examples
Check out the online help
Back here at 9:45
Manipulating vectors� Matrix transpose ´, .´ (slightly different)
Arrays can be complex>> x=[1+i, 1+2*i]
x =
1.0000 + 1.0000i 1.0000 + 2.0000i
>> x.’
ans =
1.0000 + 1.0000i
1.0000 + 2.0000i Transpose
>> x’
ans =
1.0000 - 1.0000i
1.0000 - 2.0000i Complex conjugate transpose
Manipulating vectors� Easy ways to fill up vectors
>> x=1:5 first:lastx = 1 2 3 4 5>> x = 1:0.2:2 first:step:last
x =
1.0000 1.2000 1.4000 1.6000 1.8000 2.0000
>> x = 4:-1:2 Negative step OKx = 4 3 2>> x = 1:-1:3 But set it up right!
x =
Empty matrix: 1-by-0
Manipulating vectors� Easy ways to fill up vectors
>> x=linspace(1,2,6) (first, last, N)
x =
1.0000 1.2000 1.4000 1.6000 1.8000 2.0000
>> x=linspace(3,0,10) OK to go backwards
ans =
Columns 1 through 8
3.0000 2.6667 2.3333 2.0000 1.6667 1.3333 1.0000 0.6667
Columns 9 through 10
0.3333 0
Manipulating vectors� Easy ways to fill up arrays
Array of all zeros>> zeros(2,3) rows,columns ans =
0 0 0
0 0 0
Array of all ones>> ones(3,1)
ans =
1
1
1
Manipulating vectors
Concatenating arrays>> x = [1,2]; y = [3,4];
>> [x, y]
ans =
1 2 3 4
>> [x; y]
ans =
1 2
3 4
Manipulating vectors� Extracting elements from arrays
>> x = [1 5 2 10];>> x(2)ans = Ones-based like Fortran 5 (not zeros-based like C)>> x(end)ans = 10>> x([3, 1]) You can also index with vectorsans = 2 1>> x(2:4) index by (start:end)ans = 5 2 10
Manipulating vectors� Finding elements in arrays
>> x = [-1 5 -2 10];
>> indx = find(x<0)
indx =
1 3 Returns indices of negative elements
>> x(indx) = 0
x =
0 5 0 10 The negative values have been set to zero
Vectorized computation
LOOPS(well, almost)
Vectorized computation� Example: y = cos x
Using Cint n, N;
float pi;
float x[100], y[100];
pi = 3.1415926;
N = 100;
dx = 2*pi/N;
x[0] = dx;
for(n=1;n<N;n++) {
y[n] = cos(x[n]);x[n+1] = x[n]+dx;
}
Using MATLAB
N = 100;
dx = 2*pi/N;
x = dx * (0:N-1);y = cos(x);
All mathematical functions are applied element-by-element to arrays!
#8^O
Vectorized computation� Vectorization is one key to Matlab’s power
� Example: y = e-2x cos xN = 101;x = linspace(0, 2*pi, N);y = exp(-2*x) .* cos(x);
� Example:
N = 101;x = linspace(0, 10, N);y = 1 ./ (x.^2 + 1);
y = (x2 + 1)-1
Vectorized computation� Example:
y=1 at x=0, but it’s a special case.
N = 101;x = linspace(-2, 2, N);
y = ones(1, N); Set all y values = 1
indx = find(x ~= 0); Change all values but x=0y(indx) = sin(pi*x(indx)) ./ (pi*x(indx));
y = sin πxπx
What can I compute?� Basic Matlab supplies functions for
Elementary functions (help elfun)Linear algebra (help matfun)Polynomials and interpolation (help polyfun)Data analysis and Fourier transform (help datafun)ODE solvers, minimization (help funfun)
Specialized toolboxes at Thayer forSignal and image processing (help signal, help images)Statistics Partial Differential EquationsOptimization (?)
Matlab programming
Matlab programs are called M-files
� Script M-filesA script is a list of Matlab commands
Create with Matlab editor, save as “myscript.m”
>> myscript executes the commands
Scripts are nice for hacking solutions together
Matlab programming� Function M-files
A function takes arguments and returns values function Tc = fahr2cel(Tf)
% FAHR2CEL Convert Fahrenheit to Celsius
% Tc = fahr2cel(Tf)
% Tf = temperature in Fahrenheit
% Tc = temperature in Celsius
Tc = 5/9 * (Tf - 32);
Matlab programmingUse fahr2cel.m like any other Matlab function
>> Tf = [-40 32 212];
>> fahr2cel(Tf)
ans =
-40 0 100
The first set of comments are its online help>> help fahr2cel
FAHR2CEL Convert Fahrenheit to Celsius
Tc = fahr2cel(Tf)
Tf = temperature in Fahrenheit
Tc = temperature in Celsius
Matlab programming� Matlab has if-else-end and if-elseif-else-end
IF expression statements
ELSEIF expression statementsELSE statementsEND
Also: switch (case)SWITCH switch_expression
CASE case_expression, statements .... OTHERWISE, statementsEND
Matlab programming
Sometimes (often) you really need a loopFOR expression
statements
END
WHILE expression
statements
END
Matlab programmingTo learn more about how functions are written, you can
list the M-files of many Matlab commands.
>> type fliplr%FLIPLR Flip matrix in left/right direction.% FLIPLR(X) returns X with row preserved and columns flipped% in the left/right direction.% % X = 1 2 3 becomes 3 2 1% 4 5 6 6 5 4
if ndims(x)~=2, error('X must be a 2-D matrix.'); end[m,n] = size(x);y = x(:,n:-1:1);
Advanced programming� Debugger� Profiler� File import/export� String manipulation� Data structures� Functions with variable numbers of arguments
Time for lab� Work through the examples� Write a function mybox(x) which implements the function
It can be done efficiently in three lines.� Back here at 11:00
�y = 1, |x| <= .5
0, otherwise{
Solutionfunction y = mybox(x)
% MYBOX Implement the lab assignment
y = zeros(size(x)); % Default to zeros
indx = find(abs(x) <= 0.5); % Find the points which will be 1
y(indx) = 1; % Change them
or
y(indx) = ones(size(indx));
Two-dimensional graphics� Basic plot
>> x = linspace(0, 2*pi, 51);
>> y = cos(x);
>> plot(x,y)
Two-dimensional graphics
Adding labelsLabelling commands
>> xlabel(‘x’);
>> ylabel(‘y’);
>> title(‘My First Graph’)
Interactively
Two-dimensional graphics� Points and curves
>> x = linspace(0, 2*pi, 21);
>> y = cos(x);
>> plot(x,y, x,y,’o’)
Two-dimensional graphics
� Points only>> plot(x,y,’o’)
or
>> stem(x, y)
Two-dimensional graphics� Multiple plots on the same axis
>> x = linspace(0, 2*pi, 51);
>> y = cos(x);
>> w = sin(x);
>> plot(x,y, x,w)
or
>> plot(x, y)
>> hold on This way is nice when you want to build
>> plot(x, w) a plot one graph at a time.
>> hold off
Two-dimensional graphics� Multiple plots in the same window
>> subplot(2,1,1) (m x n matrix of axes selecting pth axis)
>> plot(x,y)
>> subplot(2,1,2)
>> plot(x,w)
Two-dimensional graphics
Multiple figure windows>> figure(1)
>> plot(x,y)
>> figure(2)
>> plot(x,w)
Two-dimensional graphics� Logarithmic axes
>> x = logspace(-1, 2, 101); Between 10-1 and 102
>> y = 1 ./ x.^2 + 1;
>> semilogx(x, y) Logarithmic x axis
or
>> semilogy(x, y) Logarithmic y axis
or
>> loglog(x, y) Both axes logarithmic
� Example: decibel plot>> semilogx(x, 10 * log10(abs(y)))
Three-dimensional graphics� How to make an XY grid
>> x = linspace(0, 1, 51);
>> y = linspace(0, 1, 21);
>> [xx, yy] = meshgrid(x,y);
� Surface plotting>> z = exp(-4*(xx.^2 + yy.^2));
>> surf(x, y, z)
or
>> mesh(x, y, z)
Three-dimensional graphics� Changing the view
Command line
>> view(azimuth, elevation) Angles in degrees
Interactive (click-drag)
>> rotate3d Call once to turn on,
again to turn off
or
Rotate button on figure window
More graphics� Lines in 3-D
plot3()
� 2-D plots of 3-D datacontour() — contour plotsquiver() — vector fieldsslice() — volumetric data
� Export figures in .eps format
� And more (help graph2d, graph3d, specgraph)
Back to the lab� Work through the graphics examples
Plot y = e -2t cos t for t from 0 to 2
Plot z = e -2x cos y for x, y from 0 to 2
Wrapping up� Please email your comments to me (or slide them
under my door).
� After you’ve used Matlab for a while, send me a list of advanced topics you’d like to learn about.