Numerical Methods For Engineers
Introduction to MATLAB
Introduction to technical programming in
MATLAB!
Numerical Methods For Engineers
Introduction to MATLAB
MATLAB Desktop, when you start!
1
Numerical Methods For Engineers
Introduction to MATLAB
MATLAB stands for MATrix LABoratory
All items in MATLAB are matrices
Vectors and numbers are just special
forms of matrices
Numerical Methods For Engineers
Introduction to MATLAB
Matrices
M ti
and Arrays
2
Numerical Methods For Engineers
Introduction to MATLAB
How to enter matrices?
5
Numerical Methods For Engineers
Introduction to MATLAB
3
Numerical Methods For Engineers
Introduction to MATLAB
Numerical Methods For Engineers
Introduction to MATLAB
4
Numerical Methods For Engineers
Introduction to MATLAB
>> sum(A
sum(A')'
)
ans =
34
34
34
34
S the
So, th row sums are also
l 34!
Numerical Methods For Engineers
Introduction to MATLAB
And so is the sum of the diagonal!
((and the antidiagonal
g as well))
>> sum(diag(A))
ans =
34
To calculate the sum of the antidiagonal:
>> A(1,4)+A(2,3)+A(3,2)+A(4,1)
ans =
34
THIS IS A MAGIC SQUARE!
10
5
Numerical Methods For Engineers
Introduction to MATLAB
The colon operator
>> 1:10
ans =
1 2 3 4 5 6 7 8 9 10
>> 100:-7:50
ans =
100 93 86 79 72 65 58 51
>> sum(A(1:4,3))
ans =
34
>> sum(1:16)/4
ans =
34
11
Numerical Methods For Engineers
Introduction to MATLAB
Variable names consist of a letter, followed by
any number of letters,
letters digits,
digits or underscores.
underscores
MATLAB uses only the first 31 characters of
a variable name.
MATLAB is case sensitive; it distinguishes
between uppercase and lowercase letters.
DON'T USE MATLAB FUNCTION NAMES
AS VARIABLES!
12
6
Numerical Methods For Engineers
Introduction to MATLAB
Bad example:
>> sum = 1+2+3
sum =
6
>> sum(1:10)
??? Index exceeds matrix dimensions.
>> clear sum
>> sum(1:10)
ans =
55
ONCE AGAIN, DON'T USE MATLAB
FUNCTION NAMES AS VARIABLES!
13
Numerical Methods For Engineers
Introduction to MATLAB
14
7
Numerical Methods For Engineers
Introduction to MATLAB
Operators
+ Addition
- Subtraction
* Multiplication
/ Division
\ Left division
^ Power
' Complex conjugate transpose
( ) Specify evaluation order
15
Numerical Methods For Engineers
Introduction to MATLAB
Functions
abs, sqrt,
abs sqrt exp
exp, sin etc
etc.
>> help elfun
Elementary math functions.
Trigonometric.
sin - Sine.
sinh - Hyperbolic sine.
asin - Inverse sine.
asinh - Inverse hyperbolic sine.
cos - Cosine.
cosh - Hyperbolic cosine.
................................................................
16
8
Numerical Methods For Engineers
Introduction to MATLAB
Some useful constants
pi 3.14159265…
i Imaginary unit,
j Same as i
Inf Infinity
N N
NaN N t
Not-a-number
b
17
Numerical Methods For Engineers
Introduction to MATLAB
Examples of Expressions
rho = (1+sqrt(5))/2
rho =
1.6180
a = abs(3+4i)
a=
5
z = sqrt(besselk(4/3,rho-i))
z=
0.3730+ 0.3214i
18
9
Numerical Methods For Engineers
Introduction to MATLAB
19
Numerical Methods For Engineers
Introduction to MATLAB
20
10
Numerical Methods For Engineers
Introduction to MATLAB
21
Numerical Methods For Engineers
Introduction to MATLAB
22
11
Numerical Methods For Engineers
Introduction to MATLAB
23
Numerical Methods For Engineers
Introduction to MATLAB
24
12
Numerical Methods For Engineers
Introduction to MATLAB
25
Numerical Methods For Engineers
Introduction to MATLAB
26
13
Numerical Methods For Engineers
Introduction to MATLAB
27
Numerical Methods For Engineers
Introduction to MATLAB
Graphics
• There are two ways to handle graphics:
¾The graphic interactive tools
¾Basic plotting functions
28
14
Numerical Methods For Engineers
Introduction to MATLAB
Using the graphic tools is good for one of a kind figures.
Using the graphic functions enables you to do the same
thing with different data or at another instant in time.
"Generated Code. You can use the MATLAB M-code
generator to create code that recreates the graph. Note
that studying the generating code for a graph is a good way
to learn how to program with MATLAB."
29
Numerical Methods For Engineers
Introduction to MATLAB
Example
x = 0:pi/100:2*pi;
/ 2*
y = sin(x);
plot(x,y)
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot
title( Plot of the Sine Function'
Function ,'FontSize'
FontSize ,12)
12)
30
15
Numerical Methods For Engineers
Introduction to MATLAB
31
Numerical Methods For Engineers
Introduction to MATLAB
Several Curves in One Graph
x = 0:pi/100:2
0:pi/100:2*pi;
pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
The legend command provides an easy way to
identify the individual plots.
legend('sin(x)','sin(x-.25)','sin(x-.5)')
32
16
Numerical Methods For Engineers
Introduction to MATLAB
33
Numerical Methods For Engineers
Introduction to MATLAB
Different colors and markers
b blue . Point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star
y yellow s square
k black d diamond
v triangle (down)
^ triangle (up)
< triangleg (left)
> triangle (right)
p pentagram
h hexagram
34
17
Numerical Methods For Engineers
Introduction to MATLAB
Graphic markers
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
35
Numerical Methods For Engineers
Introduction to MATLAB
36
18
Numerical Methods For Engineers
Introduction to MATLAB
Complex Data
plot(Z)
where Z is a complex vector or matrix, is equivalent to
plot(real(Z),imag(Z))
For example,
p ,
t = 0:pi/10:2*pi;
plot(exp(i*t),'-o')
axis equal
37
Numerical Methods For Engineers
Introduction to MATLAB
38
19
Numerical Methods For Engineers
Introduction to MATLAB
Adding plots to an existing graph
[x,y,z] = peaks;
pcolor(x,y,z)
shading interp
hold on
contour(x,y,z,20,'k')
hold off
39
Numerical Methods For Engineers
Introduction to MATLAB
40
20
Numerical Methods For Engineers
Introduction to MATLAB
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)
p
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)
41
Numerical Methods For Engineers
Introduction to MATLAB
42
21
Numerical Methods For Engineers
Introduction to MATLAB
U i the
Using th Print
P i t Command
C d
[x,y,z] = peaks;
pcolor(x,y,z)
shading interp
hold on
contour(x,y,z,20,'k')
hold off
print -dbitmap myfile
43
Numerical Methods For Engineers
Introduction to MATLAB
You may then insert your figure file into a word
document for your report.
There are many formats you can use:
-dbitmap bitmap
-djpeg jpeg
-deps encapsulated postscript
-dceps encapsulated color postscript
.....................................................................
44
22
Numerical Methods For Engineers
Introduction to MATLAB
Programming
MATLAB has
h severall fl
flow control
t l constructs:
t t
“if”
“switch and case”
“for”
“while”
“continue”
“b k”
“break”
“try - catch”
“return”
We look at the most important ones!
45
Numerical Methods For Engineers
Introduction to MATLAB
If
E
Example
l
if I == J
A(I,J) = 2;
elseif abs(I-J) == 1
A(I,J) = -1;
else
A(I,J) = 0;
end
46
23
Numerical Methods For Engineers
Introduction to MATLAB
For
r = zeros(1,32)
for n = 3:32
r(n) = rank(magic(n));
end
r
47
Numerical Methods For Engineers
Introduction to MATLAB
while
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fa)
a = x; fa = fx;
else
l
b = x; fb = fx;
end
end
x
48
24
Numerical Methods For Engineers
Introduction to MATLAB
Characters and Text
>> s = 'hello'
hello
s=
hello
>> abs(s)
ans =
104 101 108 108 111
>> ss = double(s)
ss =
104 101 108 108 111
>> char(ss)
ans =
hello
49
Numerical Methods For Engineers
Introduction to MATLAB
>> S = char('A','rolling','stone','gathers','momentum.')
S=
A
rolling
stone
gathers
momentum.
>> size(S)
ans =
5 9
50
25
Numerical Methods For Engineers
Introduction to MATLAB
Scripts and Functions
There are two kinds of M-files:
Scripts, which do not accept input arguments
or return output arguments.
They operate on data in the workspace.
Functions, which can accept input arguments
and return output arguments.
Internal variables are local to the function.
51
Numerical Methods For Engineers
Introduction to MATLAB
Create a file called magicrank.m
% Investigate the rank of magic squares
r = zeros(1,32);
for n = 3:32
r(n) = rank(magic(n));
end
r
b ()
bar(r)
type magicrank
52
26
Numerical Methods For Engineers
Introduction to MATLAB
53
Numerical Methods For Engineers
Introduction to MATLAB
function r = rank(A,tol)
% RANK Matrix rank.
% RANK(A) provides an estimate of the number of linearly
% independent rows or columns of a matrix A.
% RANK(A,tol) is the number of singular values of A
% that are larger than tol.
% RANK(A) uses the default tol = max(size(A)) * norm(A) * eps.
s = svd(A);
g
if nargin==1
tol = max(size(A)') * max(s) * eps;
end
r = sum(s > tol);
54
27
Numerical Methods For Engineers
Introduction to MATLAB
>> help rank
RANK Matrix rank.
RANK(A) provides an estimate of the number of linearly
independent rows or columns of a matrix A.
RANK(A,tol) is the number of singular values of A
that are larger than tol.
RANK(A) uses th the d
default
f lt tol
t l = max(size(A))
( i (A)) * norm(A)
(A) * eps.
55
Numerical Methods For Engineers
Introduction to MATLAB
Some Important Commands
• c c – cclear command window
clc ea co a d do
• Who – shows variables in use
• Whos – shows variables in use with details
• Clear – clears all variables in the work space.
• Clear(A) – clears only the variable A
• Size(B) – gives the size of B.
• [m,n] = size(B) – gives the size assigning m for the size of rows and n for
co u
column.
• A.’ – transpose of matrix A with out conjugate complex transformation
• A’ – transpose of matrix including conjugate complex transpose
• Conj(A) – complex conjugate of A
• flipup(A) – flip upside down
• Fliplr(A) – flip left right
56
28
Numerical Methods For Engineers
Introduction to MATLAB
• Format long – will write longer precision up to 12 digits
• Format short
Format short – gives
gives shorter precision digits
shorter precision digits
• Look for ‐ searches for the string topic in the first comment
line (the H1 line) of the help text in all M‐files.
• Matlab indices starts at 1. so A(0) gives error.
• Which ‐ Locate functions and files
• fopen(filename) ‐ opens the file filename for read access
example
fid = fopen(‘FEM‐results.txt’)
st = fgetl(fid) – returns the next line of the file associated
with the file identifier fid.
fclose(fid) – to close the file.
57
Numerical Methods For Engineers
Introduction to MATLAB
• edit filename – to edit M‐file.
• axis([xmin
([ xmax yymin yymax]) ]) ‐ to change the axis of graph
g g p
• grid on – makes grid on
• Clf – clear figure
• Pwd – print working directory
• ginput ‐ enables you to select points from the figure using the
mouse for cursor positioning.
• [x y] =ginput – gives the x and y coordinates of the selected point
• text(2,3, ‘text’) –
( ‘ ’) the word text will be written on the figure at the
h d ll b h f h
specified coordinates
• text(2,3,’text’, ‘fontsize’,20) – to specify the size of the text.
• max(A) – the maximum value among the vector A
• Min(A) – minimum value
58
29
Numerical Methods For Engineers
Introduction to MATLAB
• [m, I] = max(A) – where m gives the max value and I gives
element number of the vector of the max value.
element number of the vector of the max value.
>> text(I, m, ’text’)
• num2str(m) – coverts number to string
• Str2num(m) – converts string to number.
• Colormap (A) – to get the colormap
59
30