ISE212 Chapter 3_4_ 5 MATLAB Fundamentals

advertisement
Chapters 4-3-5
MATLAB Basics
Matrices
Built-In Functions
Plotting
Arrays
Vector
Matrix
Array Fundamentals
Create: A=[2, 4, 10; 16, 3, 7];
ones(n) > nxn matrix
eye(n) > nxn
Address: A(2,3)
A(:,3) A(2,:) a(2:5) A(:)
Edit: A(2,3)=6;
Initializing Variables/Arrays
1. Assignment statement
A=[1 2 3 4]; A=[1,2; 3,4];
2. Keyboard (Colon Operator)
v=first:incr:last;
Transpose >> v=[1:4]’
input function>>V=input(‘data’);
3. Read data file:
load command (MAT-file)
Data File Commands
load > loads data from a file into the
current workspace.
Form: load filename
save > saves data from current
workspace into a file
Form: save filename var1 var2 var3
Data shared with other programs use –ascii
option: eg. save arr.dat arr –ascii
produces arr.dat file
Initializing Variables Functions
zeros(n) > n x n matrix of zeros
zeros(n,m) > n x m matrix of zeros
ones(n)
> n x n matrix of ones
ones(n,m) > n x m matrix of ones
size(arr) > returns number of rows &
columns in arr
eye(n)
> n x n identity matrix
eye(n,m) > n x m identity matrix
length(arr) > returns the length of a vector
or longest dimension
MATLAB Initializing Example
For vector v, create 6 elements in
decreasing value of 2 where the
first element is 10 and the last is 0.
[10, 8, 6, 4, 2, 0]
>>
Appending Example
B=[A r] >> appends vector r to matrix A
increases columns
B=[A;r] >> appends vector r to matrix A
increases rows
MATLAB Initializing Example
Append vector a to vector b to
create vector c.
Append vector a to vector b to
create matrix D.
a elements = 1 3 5
b elements = 7 9 11
MATLAB Initializing Example
Assume the following matrix X is stored in
the current workspace:
2 4 8 6
X= 1 7
3
4
3 5
6
9
1 2
4
5
Create a new matrix Y from X which will
produce the following matrix:
Y= 1 7
3
3 5
6
Array (element-by-element) Operations
Symbol Operation
+
.*
./
+
.*
./
.\
.^
Form
Scalar-array addition
A+b
Scalar-array subtraction A – b
Scalar-array multiplication A.*b
Scalar-array right division A./b
Array addition
A+B
Array subtraction
A–B
Array multiplication
A.*B
Array right division
A./B
Array left division
A.\B
Array Exponentiation
A.^B
Example
[6,3]+2=[8,5]
[8,3]-5=[3,-2]
[3,5].*2=[6,10]
[4,8]./4=[4/4,8/4]
[6,5]+[4,8]=[10,13]
[6,5] – [4,8]=[2,-3]
[3,5].*[4,8]=[12,40]
[2,5]./[4,8]=[2/4,5/8]
[2,5].\[4,8]=[2\4,5\8]
[3,5].^2=[9,25]
2.^[3,5]=[8,32]
[3,5].^[2,4]=[9,625]
Array Operation Example
The following table gives data for the distance
traveled along (5) truck routes and the
corresponding time required to traverse each
route. Use the data to compute the average
speed required to drive each route. Find the
route that has the highest average speed.
(Hint: [x,k]=max(a) returns the largest element
in a to x & the row index for that value to k.)
Route >>
1
2
3
4
5
Distance>> 560 440 490 530 370
Time(hrs)>> 10.3 8.2 9.1 10.1 7.5
Array Operation Example
The current i passing through an electrical
resistor having a voltage v across it is given by
i=v/r, where r is the resistance. The power
dissipated in the resistor is given by v2/r. The
following table gives data for the resistance and
voltage for (5) resistors. Use the data to compute
the current in each resistor and the power
dissipated. 1
2
3
4
5
r(ohms) 104 2x104 3.5x104 105 2x105
v(volts) 120
80
110
200 350
Matrix Operation
C = A x B (n x n)
n
ci,j =  ai,k bk,j
k=1
Matrix Operations
Symbol Operation
+
*
/
+
*
Form
Example
Scalar-matrix addition
A + b [6,3]+2=[8,5]
Scalar-matrix subtraction A – b [8,3]-5=[3,-2]
Scalar-matrix multiplication A*b
[3,5]*2=[6,10]
Scalar-matrix right division A/b
[4,8]/4=[4/4,8/4]
Matrix addition
A+B
[6,5] + [4,8]=[10,13]
Matrix subtraction
A–B
[6,5] – [4,8]=[2,-3]
Matrix multiplication
A*B
[1,2;3,4]*[1,3;1,1]=[3,5;7,13]
/ Matrix right division A/B
A * inv(B) [1,2;3,4]*[1,3;1,1]=[.5,.5;.5,2.5]
\ Matrix left division
A\B
inv(A) * B [1,2;3,4]*[1,3;1,1]=[-1,-5;1,4]
Product Cost Analysis Example
The following 2 tables show the costs &
production volume for 4 quarters associated
with 4 products. Find the (1) total quarterly costs
& the (2) total costs for the year for each of the
following categories: materials, labor, &
transportation. (Use 4 lines of code)
Unit costs ($x103)
Product Mat Labor Trans
(1)
6
2
1
(2)
2
5
4
(3)
4
3
2
(4)
9
7
3
Qtr. Production Volume
Q1 Q2 Q3 Q4
10 12 13 15
8
7 6
4
12
10 13
9
6
4 11
5
Hierarchy of Arithmetic Operations
1. Parentheses (innermost to outward)
2. Exponentials (L to R)
3. Multiplication/Division (L to R)
4. Addition/Subtraction (L to R)
Predefined Special Operators
pi 
i, j i(-1)
eg. 2i = 2 -1
Inf Infinity
NaN Not-a-Number
clock Vector [y,m,d,hour,min,sec]
date Current date eg. 13-Feb-2004
ans Stores the result of an expression
Mathematical Functions
abs(x)
absolute value
cos(x)
cosine (rad)
sin(x)
sine (rad)
tan(x)
tangent (rad)
acos(x) arc cosine (rad)
asin (x) arc sine (rad)
atan(x) arc tangent (rad)
angle(x) Phase angle (rad)
exp(x)
ex
log(x)
Natural Log (ln x)
log10(x) Base 10 Log
sqrt(x) Square Root
mod(x,y) Remainder of x/y
Rounding Functions
round(x) Rounds to nearest integer
ceil(x) Rounds up to nearest integer
floor(x) Rounds down to nearest int.
fix(x) Rounds to nearest int. towards 0
Relational Operators
<
Less than
<=
Less than or equal to
>
Greater than
>=
Greater than or equal to
==
Equal to
~=
Not equal to
Polynomial Functions
roots(x) Roots of a polynomial
(column array form)
poly(x) Coefficients of the polynomial
whose roots are specified by the array x.
polyval(a,x)
Evaluates a polynomial at specified
values of its independent variable x.
Conv(a,b) Computes the product of two
polynomials described by the coefficient
arrays a and b.
Characters in fprintf Display Function
%d Integer format
%e Exponential format
%f Floating point format
%g Floating point or exponential,
whichever is shorter
\n
Skip to a new line
Format Command
format short > 4 digits after decimal
format long > 14 digits after decimal
format short e > 5 digits plus exponent
format long e > 16 digits plus exponent
format bank > Two decimal digits
format rat > approximate ratio
x-y plotting
plot(x,y) > plots any pair of vectors
x & y versus each other
> both vectors must have
the same length
> single curve
> auto-scale spacing for
each axis
x-y plotting with fplot
fplot(y,[xmin xmax])
> x must be used for the
independent variable.
> automatically analyzes the
function & sets the plotting points
so all features of the function are
shown.
> y must be a string describing the
function.
Multiple x-y plots
plot(x,y,u,v) > plots 4-arrays:
y versus x &
v versus u
Plotting Polynomials
plot(x,polyval(a,x))
> plots the polynomial at specified
values of the independent variable.
Logarithmic Scale Plotting
plot(x,y)
> Both x&y on linear axes
semilogx(x,y) > x on logarithmic axes
semilogy(x,y) > y on logarithmic axes
loglog(x,y) > Both x&y on log axes
Specialized Plot Commands
bar(x,y)
> Bar Chart
polar(theta,r) > Polar plot
stairs(x,y) > Stairs plot
stem(x,y) > Stem plot
Subplots
subplot(m,n,p)
> displays several plots in the
same window figure
> m = number of rows
> n = number of columns
> p = pane position for next plot
Three Dimensional Line Plots
plot3(x,y,z)
> plots function of two independent
variables x & y
Label, Title, & Legend
Commands for Plotting
>>xlabel(‘string’)
>>ylabel(‘string’)
>>title(‘string’)
>>legend(‘str1’,’str2’,…,0)
>>grid on
Colors, Marker Styles, & Line Styles
>>plot(x,y,’attributestring’)
Up to 3 components allowed:
>> Line Color
>> Marker Style
>> Line Style
Color
Markers
Lines
r (red)
. (point)
- (solid)
b (blue) o (circle)
: (dotted)
g (green) * (star)
-- (dashed)
Plot Commands
gtext(‘string’)
> Place the string at a point
specified by the mouse
hold on
> Freezes the current plot for
subsequent graphics command
Stream (Text) Modifiers for Plotting
\bf
> Boldface
\it
> Italics
\fontname{fontname}
\fontsize{fontsize}
_{xxx}
> Subscripts
^{xxx}
> Superscripts
\Gamma
>
\lamda
>
\rm
> Restore normal font
Download