Upload
guest8ba004
View
1.523
Download
1
Embed Size (px)
Citation preview
1
Matlab Lecture 1 - Introduction to MATLAB
MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment. Typical uses include:
Math and computation
Algorithm development
Modeling, simulation, and prototyping
Data analysis, exploration, and visualization
Scientific and engineering graphics
MATLAB is an interactive system whose basic data element is an
array that does not require dimensioning. This allows you to solve
many technical computing problems, especially those with matrix and
vector formulations, in a fraction of the time it would take to write a program in a scalar non-interactive language such as C or Fortran.
2
Command Window
Command History
Workspace
Fig: Snap shot of matlab
3
Entering Matrices - Method 1:Direct entry
4 ways of entering matrices in MATLAB: Enter an explicit list of elements Load matrices from external data files Generate matrices using built-in functions Create matrices with your own functions in M-files
Rules of entering matrices: Separate the elements of a row with blanks or commas Use a semicolon “;“ to indicate the end of each row Surround the entire list of elements with square brackets, [ ]
To enter Dürer's matrix, simply type: » A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
MATLAB displays the matrix you just entered, A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
No need to define or declare size of A
4
Entering Matrices - as lists
Why is this a magic square? Try this in Matlab :-
» sum(A)
ans =
34 34 34 34
» A’ans = 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1 » sum(A’)’ans = 34
34 34
34
» sum(A)
ans =
34 34 34 34
» A’ans = 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1 » sum(A’)’ans = 34
34 34
34
Compute the sum of each column
in A
Result in rowvector variable
ans
Transpose matrix A
Result in columnvector variable
ans
Compute the sum of each row
in A
5
Entering Matrices - subscripts
A(i,j) refers to element in row i and column j of A :-
» A(4,2)
ans = 15
» A(1,4) + A(2,4) + A(3,4) + A(4,4)
ans = 34
» X = A;
» X(4,5) = 17X = 16 3 2 13 0 5 10 11 8 0 9 6 7 12 0 4 15 14 1 17
» A(4,2)
ans = 15
» A(1,4) + A(2,4) + A(3,4) + A(4,4)
ans = 34
» X = A;
» X(4,5) = 17X = 16 3 2 13 0 5 10 11 8 0 9 6 7 12 0 4 15 14 1 17
row colSlow way of finding
sum of column 4
Make another copyof A in X
‘;’ suppress output
Add one element in column 5, auto increase size of
matrix
6
Entering Matrices - colon : Operator
» 1:10ans = 1 2 3 4 5 6 7 8 9 10» 100:-7:50
ans = 100 93 86 79 72 65 58 51
» 0:pi/4:pi
ans = 0 0.7854 1.5708 2.3562 3.1416
» A(1:k,j);
» sum(A(1:4,4))
ans = 34
» sum(A(:,end))ans = 34
» 1:10ans = 1 2 3 4 5 6 7 8 9 10» 100:-7:50
ans = 100 93 86 79 72 65 58 51
» 0:pi/4:pi
ans = 0 0.7854 1.5708 2.3562 3.1416
» A(1:k,j);
» sum(A(1:4,4))
ans = 34
» sum(A(:,end))ans = 34
‘:’ used to specify range of numbersendstart
incr
‘0’ to ‘pi’ with incr.of ‘pi/4’
First k elements ofthe jth column in A
last colShort-cut for “all rows”
7
Expressions & built-in functions
» rho = (1+sqrt(5))/2rho = 1.6180
» a = abs(3+4i)a = 5
» z = sqrt(besselk(4/3,rho-i))z = 0.3730+ 0.3214i
» huge = exp(log(realmax))huge = 1.7977e+308
» toobig = pi*hugetoobig = Inf
» rho = (1+sqrt(5))/2rho = 1.6180
» a = abs(3+4i)a = 5
» z = sqrt(besselk(4/3,rho-i))z = 0.3730+ 0.3214i
» huge = exp(log(realmax))huge = 1.7977e+308
» toobig = pi*hugetoobig = Inf
pi 3.14159265
I or j Imaginary unit, -1
eps FP relative precision, 2-52
realmin Smallest FP number, 2-1022
realmax Largest FP number, (2-)21023
Inf Infinity
NaN Not-a-number
pi 3.14159265
I or j Imaginary unit, -1
eps FP relative precision, 2-52
realmin Smallest FP number, 2-1022
realmax Largest FP number, (2-)21023
Inf Infinity
NaN Not-a-number
Elementary functions
Complex number
Special functions
Built-in constants (function)
8
Entering Matrices Method 2: Generation
» Z = zeros(2,4)Z = 0 0 0 0 0 0 0 0
» F = 5*ones(3,3)F = 5 5 5 5 5 5 5 5 5
» N = fix(10*rand(1,10))N = 4 9 4 4 8 ...
» R = randn(4,4)R = 1.0668 0.2944 0.6918 -1.4410 0.0593 -1.3362 0.8580 0.5711 -0.0956 0.7143 1.2540 -0.3999 -0.8323 1.6236 -1.5937 0.6900
» Z = zeros(2,4)Z = 0 0 0 0 0 0 0 0
» F = 5*ones(3,3)F = 5 5 5 5 5 5 5 5 5
» N = fix(10*rand(1,10))N = 4 9 4 4 8 ...
» R = randn(4,4)R = 1.0668 0.2944 0.6918 -1.4410 0.0593 -1.3362 0.8580 0.5711 -0.0956 0.7143 1.2540 -0.3999 -0.8323 1.6236 -1.5937 0.6900
Useful Generation Functions
zeros All zeros
ones All ones
rand Uniformly distributed randomelements between (0.0, 1.0)
randn Normally distributed random
elements, mean = 0.0, var = 1.0
fix Convert real to integer
Useful Generation Functions
zeros All zeros
ones All ones
rand Uniformly distributed randomelements between (0.0, 1.0)
randn Normally distributed random
elements, mean = 0.0, var = 1.0
fix Convert real to integer
9
Entering Matrices - Method 3 & 4: Load & M-File
16.0 3.0 2.0 13.0 5.0 10.0 11.0 8.0 9.0 6.0 7.0 12.0 4.0 15.0 14.0 1.0
magik.dat
A = [ ...16.0 3.0 2.0 13.0 5.0 10.0 11.0 8.0 9.0 6.0 7.0 12.0 4.0 15.0 14.0 1.0];
magik.m
Three dots (…) meanscontinuation to next line
» magik» magik
.m files can be runby just typing itsname in Matlab
» load magik.dat » load magik.dat
Read data from fileinto variable magik
10
Entering Matrices - Concatenate & delete
» B = [A A+32; A+48 A+16] B = 16 3 2 3 48 35 34 45 5 10 11 8 37 42 43 40 9 6 7 12 41 38 39 44 4 15 14 1 36 47 46 33
64 51 50 61 32 19 18 29 53 58 59 56 21 26 27 24 57 54 55 60 25 22 23 28 52 63 62 49 20 31 30 17
» B = [A A+32; A+48 A+16] B = 16 3 2 3 48 35 34 45 5 10 11 8 37 42 43 40 9 6 7 12 41 38 39 44 4 15 14 1 36 47 46 33
64 51 50 61 32 19 18 29 53 58 59 56 21 26 27 24 57 54 55 60 25 22 23 28 52 63 62 49 20 31 30 17
» X = A;» X(:,2) = []X = 16 2 13 5 11 8 9 7 12 4 14 1
» X = A;» X(:,2) = []X = 16 2 13 5 11 8 9 7 12 4 14 1
2nd column deleted
11
MATLAB as a calculator
MATLAB can be used as a ‘clever’ calculator This has very limited value in engineering
Real value of MATLAB is in programming Want to store a set of instructions Want to run these instructions sequentially Want the ability to input data and output results Want to be able to plot results Want to be able to ‘make decisions’
12
Example revisited
Can do using MATLAB as a calculator
>> x = 1:10; >> term = 1./sqrt(x); >> y = sum(term);
Far easier to write as an M-file
n
1i
...3
1
2
1
1
1
i
1y
13
How to write an M-file
File → New → M-file Takes you into the file editor Enter lines of code (nothing happens) Save file (we will call ours L2Demo.m) Exit file Run file Edit (ie modify) file if necessary
14
n = input(‘Enter the upper limit: ‘); x = 1:n; % Matlab is case sensitive term = sqrt(x); y = sum(term)
What happens if n < 1 ?
15
n = input(‘Enter the upper limit: ‘); if n < 1
disp (‘Your answer is meaningless!’) end x = 1:n; term = sqrt(x); y = sum(term)
Jump to here if TRUE
Jump to here if FALSE
16
Example of a MATLAB Function File
function [ a , b ] = swap ( a , b )
% The function swap receives two values, swaps them,
% and returns the result. The syntax for the call is
% [a, b] = swap (a, b) where the a and b in the ( ) are the
% values sent to the function and the a and b in the [ ] are
% returned values which are assigned to corresponding
% variables in your program.
temp=a;
a=b;
b=temp;
17
Example of a MATLAB Function File
To use the function a MATLAB program could assign values to two variables (the names do not have to be a and b) and then call the function to swap them. For instance the MATLAB commands:
>> x = 5 ; y = 6 ; [ x , y ] = swap ( x , y )
result in:
x =
6
y =
5
18
MATLAB Function Files
Referring to the function, the comments immediately following the function definition statement are the "help" for the function. The MATLAB command:
>>help swap %displays:
The function swap receives two values, swaps them,
and returns the result. The syntax for the call is
[a, b] = swap (a, b) where the a and b in the ( ) are the
values sent to the function and the a and b in the [ ] are
returned values which are assigned to corresponding
variables in your program.
19
Decision making in MATLAB
For ‘simple’ decisions? IF … END (as in last example) More complex decisions? IF … ELSEIF … ELSE ... END
Example: Real roots of a quadratic equation
20
Roots of ax2+bx+c=0
Roots set by discriminant Δ < 0 (no real roots) Δ = 0 (one real root) Δ > 0 (two real roots)
MATLAB needs to make decisions (based on Δ)
a
acbbx
2
42
acb 42
21
One possible M-file
Read in values of a, b, c Calculate Δ IF Δ < 0 Print message ‘ No real roots’→ Go END ELSEIF Δ = 0 Print message ‘One real root’→ Go END ELSE Print message ‘Two real roots’ END
22
My M-file
%========================================================== % Demonstration of an m-file % Calculate the real roots of a quadratic equation %==========================================================
clear all; % clear all variables clc; % clear screen
coeffts = input('Enter values for a,b,c (as a vector): '); % Read in equation coefficients a = coeffts(1); b = coeffts(2); c = coeffts(3);
delta = b^2 - 4*a*c; % Calculate discriminant % Calculate number (and value) of real roots if delta < 0 fprintf('\nEquation has no real roots:\n\n') disp(['discriminant = ', num2str(delta)]) elseif delta == 0 fprintf('\nEquation has one real root:\n') xone = -b/(2*a) else fprintf('\nEquation has two real roots:\n') x(1) = (-b + sqrt(delta))/(2*a); x(2) = (-b – sqrt(delta))/(2*a); fprintf('\n First root = %10.2e\n\t Second root = %10.2f', x(1),x(2)) end
Header
Initialisation
Calculate Δ
Make decisions based on value of Δ
23
Command Window
ctrl-p Recall previous line ctrl-n Recall next line ctrl-b Move back one character ctrl-f Move forward one character ctrl - ctrl-r Move right one word ctrl - ctrl-l Move left one word home ctrl-a Move to beginning of line end ctrl-e Move to end of line esc ctrl-u Clear line del ctrl-d Delete character at cursor backspace ctrl-h Delete character before cursor ctrl-k Delete to end of line
ctrl-p Recall previous line ctrl-n Recall next line ctrl-b Move back one character ctrl-f Move forward one character ctrl - ctrl-r Move right one word ctrl - ctrl-l Move left one word home ctrl-a Move to beginning of line end ctrl-e Move to end of line esc ctrl-u Clear line del ctrl-d Delete character at cursor backspace ctrl-h Delete character before cursor ctrl-k Delete to end of line
24
MATLAB Graphics_ Creating a Plot
» t = 0:pi/100:2*pi;» y = sin(t);» plot(t,y)» grid» axis([0 2*pi -1 1])
» xlabel('0 \leq \itangle \leq \pi')
» ylabel('sin(t)')
» title('Graph of the sine function')
» text(1,-1/3,'\it{Demonstration of plotting}')
» t = 0:pi/100:2*pi;» y = sin(t);» plot(t,y)» grid» axis([0 2*pi -1 1])
» xlabel('0 \leq \itangle \leq \pi')
» ylabel('sin(t)')
» title('Graph of the sine function')
» text(1,-1/3,'\it{Demonstration of plotting}')
25
PLOTTING MULTIPLE CURVES IN THE SAME PLOT
There are two methods for plotting two curves in one plot:
1. Using the plot command.
2. Using the hold on, hold off commands.
26
USING THE PLOT COMMAND TO PLOT
MULTIPLE CURVES
The command:
plot(x,y,u,v) plots y versus x and v versus u on the same plot.
By default, the computer makes the curves in different colors.
The curves can have a specific style by using:
plot(x,y,’color_linestyle_marker’,u,v, ’color_linestyle_marker’)
More curves can be added.
27
Plot symbols commands
Colors Symbols Lines
y – yellow . – point - – solid line
m – mag o – circle : – dots
c – cyan x – xmark -. – line dot
r – red + – plus - - – dashes
g – green * – star
b – blue s – square
w – white d – diamond
k – black v – triangle down ^ – triangle up
< – left
< – right
p – pentagram
h – hexagram
28Ola Sbihat 28
Plot the function below on a log-log graph.
2y x>> x = logspace(-1, 1, 100);>> y = x.^2;>> loglog(x, y)A grid and additional labeling were provided and the curve is shown on the next slide.
29
30
x=[0:0.1:10];
y=500-0.5*9.81*x.^2;
xd=[0:10];
yd=[500 495 490 470 430 390 340 290 220 145 60];
plot(x,y,'g',xd,yd,'mo--')
xlabel('TIME (s)')
ylabel('HEIGHT (m)')
title('Height as a Function of Time')
legend('Model','Data')
axis([0 11 0 600])
text(1,100,'Comparison between theory and experiment')
EXAMPLE OF A FORMATTED PLOT WITH
TWO CURVESBelow is the script file of the falling object plot in lecture 4.
Creating a vector of time (data) xd
Calculated height y for each x
Creating a vector of time x
Creating a vector of height (data) yd
Plot y versus x in green, and
plot yd versus xd in magenta,
circle markers, and dashed line.
31
A PLOT WITH TWO CURVES
32
Subplots
subplot(3,2,1) subplot(3,2,2)
subplot(3,2,3)
subplot(3,2,5)
subplot(3,2,4)
subplot(3,2,6)
For example, the
command:
subplot(3,2,p)
Creates 6 plots
arranged in 3 rows
and 2 columns.
33
Example:
Plot the 3-D surface described by the equation,
in the region in the x-y plane from x = -5 to 5 and
y = -4 to 4.
Step 1) solve the equation for z,
(continued on the next slide)
2 2
4cos( )*cos( )* 0x y
x y e z
2 2
4cos( )*cos( )*x y
z x y e
3-D Plotting
34
Step 2) create two vectors x and y . The values of x and y will determine the region in the xy plane over which the surface is plotted.
>> x = linspace(-3,3,7);
>> y = linspace(-2,2,5);
Step 3) Use the meshgrid function to create two matrices, X and Y . We will use these to compute Z.
>> [X , Y] = meshgrid(x,y)
35
3 2 1 0 1 2 3
3 2 1 0 1 2 3
3 2 1 0 1 2 3
3 2 1 0 1 2 3
3 2 1 0 1 2 3
X =
Y =2 2 2 2 2 2 2
1 1 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 1 1
2 2 2 2 2 2 2
365-36
Step 4) compute Z by using the X and Y created by meshgrid,
>> R = sqrt(X.^2+Y.^2);
>> Z = cos(X).*cos(Y).*exp(-R./4)
Z =0.1673 0.0854 .1286 .2524 0.1286 0.854 0.1673
.2426 .1286 0.2050 0.4208 0.2050 .1286 .2426
.4676 .2524 0.4208 1.000 0.4208 .2524 .4676
.2426 .1286 0.2050 0.4208 0.2050 .1286 .2426
0.1673 0.0854 .1286 .2524 .1286 0.08
54 0.1673
375-37
Step 4) compute Z by using the X and Y created by meshgrid,
>> R = sqrt(X.^2+Y.^2);
>> Z = cos(X).*cos(Y).*exp(-R./4);Step 5) graph in 3-D by applying the surface function, >> surf(X,Y,Z);
38
Subplots
» t = 0:pi/10:2*pi;
» [X,Y,Z] = cylinder(4*cos(t));
» subplot(2,2,1); mesh(X)
» subplot(2,2,2); mesh(Y)
» subplot(2,2,3); mesh(Z)
» subplot(2,2,4); mesh(X,Y,Z)
» t = 0:pi/10:2*pi;
» [X,Y,Z] = cylinder(4*cos(t));
» subplot(2,2,1); mesh(X)
» subplot(2,2,2); mesh(Y)
» subplot(2,2,3); mesh(Z)
» subplot(2,2,4); mesh(X,Y,Z)
39
Mesh & surface plots
» [X,Y] = meshgrid(-8:.5:8);
» R = sqrt(X.^2 + Y.^2) + eps;
» Z = sin(R)./R;
» mesh(X,Y,Z)
» text(15,10,'sin(r)/r')
» title('Demo of 2-D plot');
» [X,Y] = meshgrid(-8:.5:8);
» R = sqrt(X.^2 + Y.^2) + eps;
» Z = sin(R)./R;
» mesh(X,Y,Z)
» text(15,10,'sin(r)/r')
» title('Demo of 2-D plot');
40
MATLAB Graphics - Subplots
Matlab official method: generate encapsulated postscript files -» print -depsc2 mesh.eps
My method:- Use <PrintScreen> key (top right corner) – or any other screen capture utility
- to capture the plot on screen Use MS Photo Editor or similar bit-map editing program to cut out the the plot
that I want Paste it into MS Word or MS PowerPoint or save it as .BMP/.GIF file Resize as necessary Fit as many as required on page Type written description (or report) if needed Print document to any printer (not necessarily postscript printer)
41
MATLAB Environment (1)
Managing Commands and Functions
addpath Add directories to MATLAB's search path
help Online help for MATLAB functions and M-files
path Control MATLAB's directory search path
Managing Variables and the Workspace
clear Remove items from memory
length Length of vector
load Retrieve variables from disk
save Save workspace variables on disk
size Array dimensions
who, whos List directory of variables in memory