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 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.
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);
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)