Sie sind auf Seite 1von 31

# -1-

## Operation Symbol Example

Subtraction - 5-3
Multiplication * 5*3
Right division / 5/3
Left division \ 5\3=3/5
Exponentiation ^ 5^3 (mean 53=125)

## Precedence Mathematical Operation

First Parentheses. For nested parentheses, the innermost are executed first
Second Exponentiation
Third Multiplication, division (equal precedence)
Note If two or more operations have the same precedence, the expression is executed from left to
right.
-2-

Example

>> 7+8/2
ans =
11
>> (7+8)/2
ans =
7.5000
>> 4+5/3+2
ans =
7.6667
>> 5^3/2
ans =
62.5000
>> 5^(3/2)
ans =
11.1803
>> 27^(1/3)+32^0.2
ans =
5
>> 27/3^2-32^0.2
ans =
1

## Command Description Example

format short Fixed-point with 4 decimal digits for: >> 391/7
0.001 number 1000 ans =
Otherwise display format short e. 55.8571
format long Fixed-point with 14 decimal digits for: >> 391/7
0.001 number 1000 ans =
Otherwise display format long e. 55.857142857142854
format short e Scientific notation with 4 decimal digits. >> 391/7
ans =
5.5857e+001
format long e Scientific notation with 15 decimal >> 391/7
digits. ans =
-3-

5.585714285714285e+001
format short g Best of 5-digit fixed or floating point. >> 391/7
ans =
55.857
format long g Best of 15-digit fixed or floating point. >> 391/7
ans =

55.8571428571429
format bank Two decimal digits. >> 391/7
ans =
55.86
format rat Ratio of small integers. >> 20/8
ans =
5/2
format compact Eliminates empty lines to allow more lines with information displayed on
the screen.
format loose Adds empty lines (opposite of compact).

## Function Description Example

sqrt(x) x >> sqrt(64)
ans =
8
nthroot(x,n) n
x >> nthroot(64,4)
ans =
2.8284
exp(x) ex >> exp(5)
ans =
148.4132
abs(x) x >> abs(-43)
ans =
43
log(x) ln(x) or log e ( x) >> log(100)
ans =
4.6052
log10(x) log 10 ( x) >> log10(100)
ans =
2
factorial(x) x! >> factorial(6)
ans =
720
-4-

## Function Description Example

sin(x) Sine of angle x (x in radians). >> sin(pi/6)
sind(x) Sine of angle x (x in degrees). ans =
0.5000
cos(x) Cosine of angle x (x in radians). >> cosd(30)
cosd(x) Cosine of angle x (x in degrees). ans =
0.8660
tan(x) Tangent of angle x (x in radians). >> tan(pi/6)
tand(x) Tangent of angle x (x in degrees). ans =
0.5774
cot(x) Cotangent of angle x (x in radians). >> cotd(30)
cotd(x) Cotangent of angle x (x in degrees). ans =
1.7321
Note pi equal to

## Function Description Example

asind(x) Arcsine of x (answer in degrees). ans =
0.5236
acosd(x) Arccosine of x (answer in degrees). ans =
60.0000
atand(x) Arctangent of x (answer in degrees). ans =
0.4636
acotd(x) Arc cotangent of x (answer in degrees). ans =
63.4349

The hyperbolic trigonometric functions are sinh(x), cosh(x), tanh(x) and coth(x).

Rounding functions

## Function Description Example

round(x) Round to the nearest integer. >> round(5.6)
ans =
6
fix(x) Round towards zero. >> fix(5.6)
ans =
5
ceil(x) Round towards infinity. >> ceil(-5.6)
ans =
-5
floor(x) Round towards minus infinity. >> floor(-5.6)
ans =
-5-

-6
rem(x,y) Returns the remainder after x is >> rem(22,5)
divide by y. ans =
2
sign(x) Signum function. >> sign(-4.5)
Returns 1 if x 0 . ans =
Returns -1 if x 0 . -1
Returns 0 if x 0 .

Assignment Calculate:

28.5 3 2 1500
1. ?
112 37.3

2.
24 4.53 ?
e 4.4 log(12560)

tan ln 8
5 2 7 6 ?
3. cos sin
6 8 7 2

## Variable_name = A numerical value, or a computable expression

Example

>> a=12
a =
12
>> B=4
B =
4
>> C=(a-B)+40-a/B*10
C =
18

>> a=12;
>> B=4;
>> C=(a-B)+40-a/B*10;
>> C
-6-

C =
18

a =
12
C =
18

## Must begin with a letter.

Can be up to 63 characters long.
Can contain letters, digits, and the underscore character.
Cannot contain punctuation charactors (e.g. period, comma, semicolon).
MATLAB is case sensitive; it distinguishes between uppercase and lowercase letters.
No spaces are allowed between charactors(use the underscore where a space is desired).
Avoid using the names of a built-in function for a variable.

## 1.8 Predefined Variables and keywords

There are seventeen keywords that are reserved by MATLAB. Cannot be used as variable names.

break case catch continue else elseif end for function global
if otherwise persistent return switch try while

## ans A variable that has the value of the last expression.

pi The number .

eps The smallest difference between two numbers, which is approximately 2.2204e-016.

j Same as i.

-7-

## 1.9 Useful Command for Managing Variables

Command Outcome
clear Removes all variables from the memory.
clear x y z Removes only variable x, y, and z from the memory.
who Display a list of the variables currently in the memory.
whos Display a list of the variables currently in the memory and their size together
with information about their bytes and class.

Assignment

1. Define two variables: alpha=5/9, beta=/7. Using these variables, show that the following
trigonometric identity is correct by calculating the value of the left-and right-hand sides of the
equation.
1
sin sin cos cos
2
2. The temperature dependence of vapor pressure p can be estimated by the Antoine equation:
B
ln p A
C T
Where ln is the natural logarithm, p is in mm Hg, T is in Kelvin, and A,B, and C are material
constants. For toluene(C6H5CH3) in the temperature range from 280 to 410 K the material
constants are: A = 16.0137, B = 3096.52, and C = -53.67. Calculate the vapor pressure of toluene
at 315 and 405 K.
-8-

## Ch. 2 Creating Arrays

Scalar 25

Vector

Row vector 10 20 30

1
5
Column vector
6

7

2 3 1 2 10
matrix ,
4 5 22 5 6 1 23

## Variable_name = [ type vector elements]

Variable_name = [m:q:n]

Or Variable_name = m:q:n

q is step size

n is end value

## Variable_name = [m:n] if q=1

Variable_name=linspace(xi , xf ,n)

xf is end value

## n is the number of point

-9-

Example

>> PNTAH=[2,3,4 5]
PNTAH =
2 3 4 5
>> PNTAV=[2;3;4;5]
PNTAV =
2
3
4
5
>> x=[1:2:14]
x =
1 3 5 7 9 11 13
>> y=[-3:7]
y =
-3 -2 -1 0 1 2 3 4 5 6 7
>> w=linspace(2,12,7)
w =
2.0000 3.6667 5.3333 7.0000 8.6667 10.3333 12.0000

## 2.2 Creating Matrix

Variable_name=[ 1st row element; 2nd row element; 3rd row element; ; last row element+

Example

## >> a=[5 35 43; 4 76 81; 21 32 40]

a =
5 35 43
4 76 81
21 32 40
>> a=[5 35 43; 4 76 81; 21 32 40]
a =
5 35 43
- 10 -

4 76 81
21 32 40
>> b=[3 -4 5;3,4,9]
b =
3 -4 5
3 4 9

zeros(m,n) [0]mn

ones(m,n)[1]mn

eye(n)[I]nn

Example

>> zr=zeros(3,4)
zr =
0 0 0 0
0 0 0 0
0 0 0 0
>> ne=ones(4,3)
ne =
1 1 1
1 1 1
1 1 1
1 1 1
>> idn=eye(3)
idn =
1 0 0
0 1 0
0 0 1

## 2.4 The Transpose Operation

The transpose operator is applied by typing a single quote ' following the variable to be transposed.
- 11 -

Example

>> aa=[2 7 9]
aa =
2 7 9
>> bb=aa'
bb =
2
7
9
>> C=[1 5 -2;4 5 8]
C =
1 5 -2
4 5 8
>> D=C'
D =
1 4
5 5
-2 8

Vector

## For a vector named ve, ve(i) refers to the element in position i.

Example

>> VCT=[3 6 9 7 5 -2 8]
VCT =
3 6 9 7 5 -2 8
>> VCT(3)
ans =
9
>> VCT(5)
ans =
5
>> VCT(3)+VCT(5)
ans =
- 12 -

14
>> VCT(3)^VCT(6)
ans =
0.0123

Matrix

For a matrix named ma, ma(i,j) refers to the element in row i and column j.

Example

## >> MAT=[3 4 5;8 9 11]

MAT =
3 4 5
8 9 11
>> MAT(2,3)
ans =
11
>> MAT(2,3)/MAT(1,2)
ans =
2.7500

## 2.6 Using a Colon : In Addressing Arrays

For a vector:

va(:) Refers to all the elements of the vector va (either a row or column vector).

Example

v =
4 5 6 7 9 3 13
>> u=v(3:6)
u =
6 7 9 3
For a matrix:
- 13 -

## A(n,:) Refers to the elements in all column of row n of the matrix A.

A(:,m,n) Refers to the elements in all rows between column m and n of matrix A.

A(m,n,:) Refers to the elements in all columns between row m and n of matrix A.

A(m:n,p:q) Refers to the elements in rows m through n and column p through q of matrix A.

Example

A =
1 2 3 4 5
5 6 10 30 -5
4 8 9 -1 2
>> B=A(:,3)
B =
3
10
9
>> C=A(2,:)
C =
5 6 10 30 -5
>> E=A(:,2:4)
E =
2 3 4
6 10 30
8 9 -1
>> F=A(1:2,2:4)
F =
2 3 4
6 10 30
- 14 -

## Function Description Example

length(A) Returns the number of elements in >> A=[4 5 -2 4]
the vector A. A =
4 5 -2 4
>> length(A)
ans =
4
size(A) Returns a row vector [m,n], >> A=[4 5 -2 4;1 -9 8 7]
where m and n are the size mn of A =
the array A. 4 5 -2 4
1 -9 8 7
>> size(A)
ans =
2 4
diag(A) When A is a matrix, creates a vector >> A=[2 4 5;-3 -5 9;0 2 6]
from the diagonal elements of A. A =
2 4 5
-3 -5 9
0 2 6
>> diag(A)
ans =
2
-5
6
- 15 -

## In general, if A and B are two arrays:

A A12 A13 B11 B12 B13
A 11 and B
A21 A22 A23 23 B21 B22 B23 23
Then, the matrix that is obtained by adding, or subtracting, A and B is:
A B11 A12 B12 A12 B13
A B 11
A21 B21 A22 B22 A23 B23 23

Example

## >> V_A=[2 3 -5];V_B=[3 -4 6];

>> V_C=V_A+V_B
V_C =
5 -1 1
>> A=[10 7 9;4 -5 8]
A =
10 7 9
4 -5 8
>> B=[3 4 -6;20 4 -2]
B =
3 4 -6
20 4 -2
>> A-B
ans =
7 3 15
-16 -9 10
>> C=A+B
C =
13 11 3
24 -1 6
>> C-4
ans =
- 16 -

9 7 -1

20 -5 2

## 3.2 Array Multiplication

The multiplication operation * is executed by MATLAB according to the rules of linear algebra. If A and
B are two matrices, the operation A*B can be carried out only if the number of columns in matrix A is
equal to the number of rows in matrix B.

Example

## >> A=[1,2,3;4 -5 8;4 9 1;6 7 8]

A =
1 2 3
4 -5 8
4 9 1
6 7 8
>> B=[6 1;2 5;7 3]
B =
6 1
2 5
7 3
>> C=A*B
C =
31 20
70 3
49 52
106 65

## 3.3 Element-By-Element Operations

Symbol Description
.* Multiplication
.^ Exponentiation
./ Right division
.\ Left division
- 17 -

## If two vector A and B are:

A [a1 a2 a3 a n ]
B [b1 b2 b3 bn ]

## then element-by-element operation gives

A B [a1 b1 a 2 b2 a3 b3 a n bn ]
A . * B [a1b1 a 2 b2 a3b3 a n bn ]
A .^ B [a1 1 a 2 b a3 b a n b
b 2 3
n
]
A . / B [a1 / b1 a 2 / b2 a3 / b3 a n / bn ]
A . \ B [a1 \ b1 a 2 \ b2 a3 \ b3 a n \ bn ]

## Define c as scalar then

A c [a1 c a 2 c a3 c a n c]
A * c [a1 * c a 2 * c a3 * c a n * c]
A .^ c [a1 a 2 c a3 c a n c ]
c

A / c [a1 / c a 2 / c a3 / c a n / c]
A \ c [a1 \ c a 2 \ c a3 \ c a n \ c]

## >> A=[2 6 3;5 8 4]

A =
2 6 3
5 8 4
>> B=[1 4 10;3 2 9]
B =
1 4 10
3 2 9
>> A.*B
ans =
2 24 30
15 16 36
>> A./B
ans =
2.0000 1.5000 0.3000
- 18 -

>> B.^4
ans =
1 256 10000
81 16 6561

## Function Description Example

sum(A) 1. If A is a vector, returns the >> A=[5 9 6 8];
sum of the elements of the >> sum(A)
vector. ans =
2. If A is a matrix, returns the 28
sum of the elements of each >> A=[5 9 6 8;1 6 7 4]
A =
column.
5 9 6 8
1 6 7 4
>> sum(A)
ans =
6 15 13 12
det(A) Returns the determinant of a square >> A=[2 4;7 8];
matrix A. >> det(A)
ans =
-12
dot(a,b) Calculates the scalar(dot) product of >> A=[2 5 6];
two vector a and b. >> B=[1 8 4];
>> dot(A,B)
ans =
66
cross(a,b) Calculates the vector(cross) product >> A=[2 5 6];
of two vector a and b. >> B=[1 8 4];
>> cross(A,B)
ans =
-28 -2 11
inv(A) Returns the inverse of a square >> A=[1 2 3;4 5 7;9 3 1];
matrix A. >> inv(A)
ans =
-5.3333 2.3333 -0.3333
19.6667 -8.6667 1.6667
-11.0000 5.0000 -1.0000
- 19 -

Assignment

1. Write only three commands to compute the volume of cone, which have various height and
radius as shown in table, by using a following formula

1
V r 2 h
3

r 1 2 3 4 5 6 7 8 9 10
H 5 10 15 20 25 30 35 40 45 50
V

2. Define x and y as the vectors x = 2,4,6,8,10 and y=3,6,9,12,15. Then use them in the following
expression to calculate z using element-by-element calculations
2
y yx
z x y x
x

## 3. Solve the following system of five linear equations:

1.5 x 2 y z 3u 0.5w 7.5
3 x y z 4u 3w 16
2 x 6 y 3z u 3w 78
5 x 2 y 4 z 2u 6 w 71
3 x 3 y 2 z 5u 4w 54
- 20 -

CH 4 Script Files

## 1. Input to Script Files

a) Assign value in the script file
b) Assign value in the command window
c) Using input command

## Variable_name=input(string with a message that is displayed in the command window)

2. Output Commands
a) The disp command
disp(name of a variable)
disp(*variable#1,variable#2,+)
disp(text as string)
b) The fprintf command
fprintf(text typed in as a string)
fprintf(text as string %-5.2f additional text, variable_name)

## Formatting Elements are:

-5.2f
Flag Field width Conversion character (required)

(optional)

## Character used for flag Description

- (minus sign) Left justifies the number within the field.
+(plus sign) Prints a sign character (+ or -) in front of the number.
0 (zero) Adds zeros if the number is shorter than the field.

- 21 -

## G The shorter of E or f notations.

i Integer.

Example Write a script files to calculate the mean and the standard deviation of sample.

x i
x i 1

n
n

x x
2
i
SD i 1

n 1

Type I

x=[1 2 3 4 5 6];
n=length(x);
mean_x=sum(x)/n;
SD=sqrt(sum((x-mean_x).^2)/(n-1));
disp([mean_x,SD])
Type II

## x=input('the sampling data =');

n=length(x);
mean_x=sum(x)/n;
SD=sqrt(sum((x-mean_x).^2)/(n-1));
disp([mean_x,SD])
Type III

## x=input('the sampling data =');

n=length(x);
mean_x=sum(x)/n;
SD=sqrt(sum((x-mean_x).^2)/(n-1));
fprintf('The mean is %-5.3f \n',mean_x);
fprintf('The standard deviation is %-5.3f \n',SD);
- 22 -

CH 5 Two-Dimensional Plots

plot(x,y)

## >> x=[1 2 3 5 7 7.5 8 10];

>> y=[2 6.5 7 7 5.5 4 6 8];
>> plot(x,y)

Plot(x,y,line specifiers,PropertyName,PropertyValue)

Line Specifiers

solid(default) -
dashed --
dotted :
dash-dot -.
- 23 -

red r
green g
blue b
cyan c
magenta m
yellow y
black k
white w

## Marker Type Specifier Marker Type Specifier

plus sign + square s
circle o diamond d
asterisk * five-pointe star p
point . six-pointded star h
cross x triangle(pointed left) <
triangle (pointed up) ^ triangle(pointed right) >
triangle (pointed down) v

Some examples:

plot(x,y) A blue solid line connects the point with no markers (default).

## plot(x,y,y) A yellow dashed line connects the points.

plot(x,y,*) The points are marks with * (no line between the points).

plot(x,y,g:d) A green dotted line connects the points that are marked with diamond markers.

## Property Name Description Possible Property Values

LineWidth (or linewidth) Specifies the width of the line. A number in units of points
(default 0.5)
MarkerSize (or Specifies the size of the marker A number in unit of points.
markersize)
MarkerEdgeColor (or Specifies the color of the marker, Color specifiers from the table
markeredgecolor) or the color of the edge line for above, typed as a string
- 24 -

filled markers.
MarkerFaceColor (or Specifies the color of the filling Color specifiers from the table
markerfacecolor) for filled markers. above, typed as string.

## 5.2 Using the plot command to plot multiple graphs

plot(x1,y1,x2,y2,,xn,yn)

Example

Plot the function y=3x3-20x+12 and its first and second derivatives, for -2x4, all in the same
plot

Solution

## >> fplot('x^2+5*sin(3*x)-3',[-3 3])

>> x=[-2:0.001:4];
>> y=3*x.^3-20*x+12;
>> yd=9*x.^2-20;
>> ydd=18*x;
>> plot(x,y,'-b',x,yd,'--r',x,ydd,':k')

140

120

100

80

60

40

20

-20

-40
-2 -1 0 1 2 3 4
- 25 -

## 5.3 The fplot Command

fplot(function,limit,line specifiers)

function: The function can be typed directly as a string inside the command.

limits: The limits is a vector with two element that specify the domain of x
[xmin,xmax], or a vector with four elements that specifies the domain of x
and the limits of the y-axis [xmin,xmax,ymin,ymax].

Line specifiers : The line specifiers are the same as in the plot command.

10

-2

-4

-6

-8
-3 -2 -1 0 1 2 3

## 5.4 The xlabel and ylabel commands

xlabel(text as string)
ylabel(text as string)

## 5.5 The title command

title(text as string)
- 26 -

## 5.6 The axis command

axis([xmin,xmax,ymin,ymax]) Set the limits of both the x and y axes.
axis equal Set the same scale for both axes.
axis square Set the axes region to be square.
axis tight Set the axis limits to the range of the data.

## 5.7 The grid command

grid on Add grid lines to the plot.
grid off Removes grid lines from the plot.

>> x=[-2:0.001:4];
>> y=3*x.^3-20*x+12;
>> yd=9*x.^2-20;
>> ydd=18*x;
>> plot(x,y,'-b',x,yd,'--r',x,ydd,':k')
>> x=[10:0.1:22];
>> y=95000./x.^2;
>> plot(x,y,'-','LineWidth',1.0)
>> xlabel('DISTANCE (cm)')
>> ylabel('INTENSITY (lux)')
>> title('Light Intensity as a Function of Distance')
>> axis([8 24 0 1200])
>> grid on
Light Intensity as a Function of Distance
1200

1000

800
INTENSITY (lux)

600

400

200

0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
- 27 -

## All variables are local variables except using this command:

global variable_name

Example Write a function files to calculate the mean and the standard deviation of sample.

x i
x i 1

n
n

x x
2
i
SD i 1

n 1

function [mean_x,SD]=mean_SD(x)
n=length(x);
mean_x=sum(x)/n;
SD=sqrt(sum((x-mean_x).^2)/(n-1));
- 28 -

Ch 7 Programming in MATLAB

## Relational Operator Description

< Less than.
> Greater than.
<= Less than or equal to.
>= Greater than or equal to.
== Equal to.
~= Not Equal to.

## 7.2 Logical Operators

Logical Operator Name Description
& AND Operates on two operands (A and B). If both
are true, the result is true (1), otherwise the
result is false (0).
| OR Operates on two operands (A and B). If either
one, or both are true, the result is true(1),
otherwise (both are false) the result is false
(0).
~ NOT Operates on one operand (A). Gives the
opposite of the operand. True (1) if the
operand is false, and false (0) if the operand is
true.

## 7.3.1) The if-end Structure

if conditional expression
. . .
. . . A group of MATLAB commands
. . .
end

x=2;
if x>=1
x=x+3;
end
- 29 -

disp(x)

## 7.3.2) The if-else-end Structure

if conditional expression
. . .
. . . Group 1 of MATLAB commands
. . .
else
. . .
. . . Group 2 of MATLAB commands
. . .
end
x=2;
if x>=5
x=x+4;
else
x=x+2;
end
disp(x)

## 7.3.3) The if-elseif-else-end Structure

if condition#1
. . .
. . . Group 1 of MATLAB commands
. . .
elseif condition#2
. . .
. . . Group 2 of MATLAB commands
. . .
else
. . .
. . . Group 3 of MATLAB commands
. . .
end
Assignment
Write a function file to compute a following function
- 30 -

20 x 5

f ( x) 5 x 10 5 x 10
10 x 2 35 x 20 x 10

And calculate f 6 , f 0

7.4 Loops
7.4.1) The for-end Loops
for k=f:s:t
. . .
. . . A group of MATLAB commands
. . .
end
k = index variable
f = first value
s = step size
t = end value

20
1
Example Compute 2i 12i 2
i 1

s=0;
for i=1:1:20
s=s+1/((2*i+1)*(2*i+2));
end
disp(s)

## 7.4.2) The while-end Loops

while conditional expression
. . .
. . . A group of MATLAB commands
. . .
end
- 31 -

20
1
Example Compute 2i 12i 2
i 1

s=0;
i=1;
while i<=20
s=s+1/((2*i+1)*(2*i+2));
i=i+1;
end
disp(s)