Interactive Computing With: Matlab
Interactive Computing With: Matlab
with Matlab
Gerald W. Recktenwald
Department of Mechanical Engineering
Portland State University
[email protected]
The latest version of this PDF file, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.
Helpwin Window
Plot Window
Command Window
Command Prompt:
Enter typed commands here. Recent Directory Menu:
Text results are displayed here. Used to change current
working directory.
>> ans/2
ans =
2
>> a = 5
a =
5
>> b = 6
b =
6
>> c = b/a
c =
1.2000
>> pi
ans =
3.1416
>> sin(ans/4)
ans =
0.7071
>> log(256)
ans =
5.5452
>> log10(256)
ans =
2.4082
>> log2(256)
ans =
8
Syntax:
lookfor string
Example:
>> lookfor cosine
produces
Syntax:
help functionName
Example:
>> help log
produces
Example:
Assign values to x, y, and z, but only display the value of z in
the command window:
>> x = 5;
>> y = sqrt(59);
>> z = log(y) + x^0.25
z =
3.5341
Type variable name and omit the semicolon to print the value of
a variable (that is already defined)
>> y
y =
7.6811 ( = log(sqrt(59)) + 5^0.25 )
c =
74.2099
Examples:
xxxxxxxxx
pipeRadius
widgets_per_baubble
mySum
mysum
Name Meaning
ans value of an expression when that expression
is not assigned to a variable
eps floating point precision
pi π, (3.141492 . . .)
realmax largest positive floating point number
realmin smallest positive floating point number
Inf ∞, a number larger than realmax,
the result of evaluating 1/0.
NaN not a number, the result of evaluating 0/0
√
Exception: i and j are preassigned to −1. One or both of
i or j are often reassigned as loop indices. More
on this later
• Creating vectors:
linspace and logspace
• Creating matrices:
ones, zeros, eye, diag, . . .
• Subscript notation
• Colon notation
• Vectorization
>> x = expression
>> v = [7 3 9]
v =
7 3 9
>> w = [2; 6; 1]
w =
2
6
1
>> v = [2 4 1 7]
v =
2 4 1 7
>> v’
ans =
2
4
1
7
>> A = [1 2 3; 4 5 6; 7 8 9 ]
A =
1 2 3
4 5 6
7 8 9
>> A’
ans =
1 4 7
2 5 8
3 6 9
>> x = 2;
>> x = x + 2
x =
4
>> y = [1 2 3 4]
y =
1 2 3 4
>> y = y’
y =
1
2
3
4
Syntax:
x = linspace(startValue,endValue)
x = linspace(startValue,endValue,nelements)
Examples:
>> u = linspace(0.0,0.25,5)
u =
0 0.0625 0.1250 0.1875 0.2500
>> u = linspace(0.0,0.25);
>> v = linspace(0,9,4)’
v =
0
3
6
9
Syntax:
x = logspace(startValue,endValue)
x = logspace(startValue,endValue,nelements)
Example:
>> w = logspace(1,4,4)
w =
10 100 1000 10000
Syntax:
A = ones(nrows,ncols)
A = zeros(nrows,ncols)
Examples:
>> D = ones(3,3)
D =
1 1 1
1 1 1
1 1 1
>> E = ones(2,4)
E =
0 0 0 0
0 0 0 0
ones and zeros are also used to create vectors. To do so, set
either nrows or ncols to 1.
>> s = ones(1,4)
s =
1 1 1 1
>> t = zeros(3,1)
t =
0
0
0
Syntax:
A = eye(n)
A = eye(nrows,ncols)
Examples:
>> C = eye(5)
C =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
>> D = eye(3,5)
D =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
Syntax:
A = diag(v)
v = diag(A)
Example:
Use diag to create a matrix
>> v = [1 2 3];
>> A = diag(v)
A =
1 0 0
0 2 0
0 0 3
Example:
Use diag to extract the diagonal of a matrix
>> w = diag(B)
w =
1
6
11
>> A = [1 2 3; 4 5 6; 7 8 9];
>> b = A(3,2)
b =
8
>> c = A(1,1)
c =
1
>> A = [1 2 3; 4 5 6; 7 8 9];
>> A(1,4)
??? Index exceeds matrix dimensions.
>> A = [1 2 3; 4 5 6; 7 8 9];
A =
1 2 3
4 5 6
7 8 9
>> A(4,4) = 11
A =
1 2 3 0
4 5 6 0
7 8 9 0
0 0 0 11
Syntax:
startValue:endValue
startValue:increment:endValue
>> s = 1:4
s =
1 2 3 4
>> t = 0:0.1:0.4
t =
0 0.1000 0.2000 0.3000 0.4000
>> u = (1:5)’
u =
1
2
3
4
5
>> v = 1:5’
v =
1 2 3 4 5
>> A = [1 2 3; 4 5 6; 7 8 9];
>> A(:,1)
ans =
1
4
7
>> A(2,:)
ans =
4 5 6
>> A(2:3,1)
ans =
4
7
>> A(1:2,2:3)
ans =
ans =
2 3
5 6
Example:
>> A = ones(8,8);
>> A(3:6,3:6) = zeros(4,4)
A =
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 0 0 0 0 1 1
1 1 0 0 0 0 1 1
1 1 0 0 0 0 1 1
1 1 0 0 0 0 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
Examples:
>> x = 1:4;
>> y = x(:)
y =
1
2
3
4
>> A = rand(2,3);
>> v = A(:)
v =
0.9501
0.2311
0.6068
0.4860
0.8913
0.7621
0.4565
Note: The rand function generates random elements between zero and
one. Repeating the preceding statements will, in all likelihood,
produce different numerical values for the elements of v.
• Complex Numbers
• Strings
• Polynomials
>> sqrt(-4)
ans =
0 + 2.0000i
>> y = 1 - 2*i
y =
1.0000 - 2.0000i
>> z = x*y
z =
5
>> i^2
ans =
-1
>> i = 5;
>> t = 8;
>> u = sqrt(i-t) (i-t = -3, not -8+i)
u =
0 + 1.7321i
>> u*u
ans =
-3.0000
>> A = [1 2; 3 4];
>> i = 2;
>> A(i,i) = 1
A =
1 2
3 1
imaginary
iy z = ζ eiθ
ζ
θ
x real
Function Operation
abs Compute the magnitude of a number
abs(z) is equivalent to
to sqrt( real(z)^2 + imag(z)^2 )
angle Angle of complex number in Euler notation
exp If x is real,
exp(x) = ex
If z is complex,
exp(z) = eRe(z) (cos(Im(z) + i sin(Im(z))
conj Complex conjugate of a number
imag Extract the imaginary part of a complex number
real Extract the real part of a complex number
Examples:
>> zeta = 5; theta = pi/3;
>> z = zeta*exp(i*theta)
z =
2.5000 + 4.3301i
>> abs(z)
ans =
5
>> sqrt(z*conj(z))
ans =
5
>> x = real(z)
x =
2.5000
>> y = imag(z)
y =
4.3301
>> angle(z)*180/pi
ans =
60.0000
Examples:
>> first = ’John’;
>> last = ’Coltrane’;
>> name = [first,’ ’,last]
name =
John Coltrane
>> length(name)
ans =
13
>> name(9:13)
ans =
trane
Function Operation
char convert an integer to the character using ASCII codes,
or combine characters into a character matrix
findstr finds one string in another string
length returns the number of characters in a string
num2str converts a number to string
str2num converts a string to a number
strcmp compares two strings
strmatch identifies rows of a character array that begin
with a string
strncmp compares the first n elements of two strings
sprintf converts strings and numeric values to a string
Examples:
>> msg1 = [’There are ’,num2str(100/2.54),’ inches in a meter’]
message1 =
There are 39.3701 inches in a meter
>> strcmp(msg1,msg2)
ans =
0
>> strncmp(msg1,msg2,9)
ans =
1
>> findstr(’in’,msg1)
ans =
19 26
Example:
Evaluate x3 − 2x + 12 at x = −1.5
>> c = [1 0 -2 12];
>> polyval(c,1.5)
ans =
12.3750
Example:
>> u = [10 9 8]; (u and v are row vectors)
>> v = [1 2 3];
>> u+v
ans =
11 11 11
>> u-v
ans =
9 7 5
Example:
>> x = 0:pi/4:pi (define a row vector)
x =
0 0.7854 1.5708 2.3562 3.1416
real x(5),y(5)
pi = 3.14159624
dx = pi/4.0
do 10 i=1,5
x(i) = (i-1)*dx
y(i) = sin(x(i))
10 continue
More examples
>> A = pi*[ 1 2; 3 4]
A =
3.1416 6.2832
9.4248 12.5664
>> S = sin(A)
S =
0 0
0 0
>> B = A/2
B =
1.5708 3.1416
4.7124 6.2832
>> T = sin(B)
T =
1 0
-1 0
Symbol Operation
.* element-by-element multiplication
./ element-by-element “right” division
.\ element-by-element “left” division
.^ element-by-element exponentiation
Examples:
Element-by-element multiplication and division
>> u = [1 2 3];
>> v = [4 5 6];
>> w = u.*v (element-by-element product)
w =
4 10 18
Examples:
Application to matrices
>> A = [1 2 3 4; 5 6 7 8];
>> B = [8 7 6 5; 4 3 2 1];
>> A.*B
ans =
8 14 18 20
20 18 14 8
>> A*B
??? Error using ==> *
Inner matrix dimensions must agree.
>> A*B’
ans =
60 20
164 60
>> A.^2
ans =
1 4 9 16
25 36 49 64
>> a = 5; b = 2; c = 1;
>> d(1) = sqrt(b^2 - 4*a*c);
>> d(2) = -d(1);
>> who
Your variables are:
a b c d
The whos command lists the name, size, memory allocation, and
the class of each variables defined in the workspace.
>> whos
save fileName
save fileName variable1 variable2 ...
save fileName variable1 variable2 ... -ascii
load fileName
load fileName matrixVariable
Example:
Load data from a file and plot the data
Matlab will only use those functions and data files that are in
its path.
>> p = path;
>> path(p,’N:\IMAUSER\ME352\PS2’);
>> p = path;
>> path(p,’~/matlab/ME352/ps2’);
Syntax:
plot(x,y)
plot(xdata,ydata,symbol)
plot(x1,y1,x2,y2,...)
plot(x1,y1,symbol1,x2,y2,symbol2,...)
Example:
A simple line plot
>> x = linspace(0,2*pi);
>> y = sin(x);
>> plot(x,y);
0.5
-0.5
-1
0 2 4 6 8
The curves for a data set are drawn from combinations of the
color, symbol, and line types in the following table.
Examples:
Put yellow circles at the data points:
plot(x,y,’yo’)
plot(x,y,’r--’)
plot(x,y,’kd--’)
Example:
>> x = linspace(0,3);
>> y = 10*exp(-2*x);
>> plot(x,y);
10
0
0 1 2 3
>> semilogy(x,y);
1
10
0
10
-1
10
-2
10
0 1 2 3
Syntax:
subplot(nrows,ncols,thisPlot)
Repeat the values of nrows and ncols for all plots in a single
figure window. Increment thisPlot for each plot
Example:
>> x = linspace(0,2*pi);
>> subplot(2,2,1);
>> plot(x,sin(x)); axis([0 2*pi -1.5 1.5]); title(’sin(x)’);
>> subplot(2,2,2);
>> plot(x,sin(2*x)); axis([0 2*pi -1.5 1.5]); title(’sin(2x)’);
>> subplot(2,2,3);
>> plot(x,sin(3*x)); axis([0 2*pi -1.5 1.5]); title(’sin(3x)’);
>> subplot(2,2,4);
>> plot(x,sin(4*x)); axis([0 2*pi -1.5 1.5]); title(’sin(4x)’);
sin(x) sin(2x)
1.5 1.5
1 1
0.5 0.5
0 0
-0.5 -0.5
-1 -1
-1.5 -1.5
0 2 4 6 0 2 4 6
sin(3x) sin(4x)
1.5 1.5
1 1
0.5 0.5
0 0
-0.5 -0.5
-1 -1
-1.5 -1.5
0 2 4 6 0 2 4 6
>> plot(m,t(:,1),’ro’,m,T(:,2),’k+’,m,T(:,3),’b-’);
>> xlabel(’Month’);
>> ylabel(’Temperature ({}^\circ F)’);
>> title(’Monthly average temperature at PDX’);
>> axis([1 12 20 100]);
>> legend(’High’,’Low’,’Average’,2);
80
Temperature ( F)
70
°
60
50
40
30
20
2 4 6 8 10 12
Month