Вы находитесь на странице: 1из 35

# Spring 2015

MATLAB Chapter 1
An Overview of MATLAB

MATLAB

##  Extremely useful mathematical software

 Can be used as an advanced calculator/graphing tool
 Can be used as a powerful programming language

1
Spring 2015

programming.

environment.

##  Programming is a TRANSFERABLE SKILL

 Programming concepts are common for all languages
 Syntax may change, but usually similar

##  MATLAB is and INDEPENDENT PLATFORM

 Can write software once for many Operating Systems

##  MATLAB can be linked to other software

 C/C++, Fortran, etc…

2
Spring 2015

MATLAB in University/Industry

models.

##  MATLAB can be used to develop and analyze new

models. For example, in like
 Structural Analysis
 Electric Circuits Analysis
 Communication Systems
 Systems and Control

## 1.1 Starting Matlab

This window
shows the current
directory or the This is the
workspace command
This window window
shows the
command
history

3
Spring 2015

##  You can enter expressions at the command line and

evaluate them right away.

command
ans =
0.8000
next
command
>>

7

##  Just like Excel, we use the notation “e” to represent

exponentiation
 Example: 5.316×102
In Matlab: 5.316e+02

4
Spring 2015

1.1 Variable

##  Matlab has assigned the answer to a variable called

ans, which contains the most recent answer.

##  ans can be used for further calculations.

 Example: >> 5*ans

ans =
4
>>
9

1.1 Variable

##  You can also use variables >> temp1_a=50

letter, can include numbers 50
and underscores: >>temp1_a/2
 For example: temp1_a can
be used as a variable. ans =
 Note: Matlab is case- 25
sensitive. >>
10

5
Spring 2015

##  Matlab has 100s of built-in functions. >> sqrt(9)

 Example: the square root
function ans =
 In Matlab: sqrt(x), where x can
e.g. be a number, a variable or
3
an array…
>>
 Attention: It is possible to assign
See Table 1.3-1 and Appendix A
variable names with built-in
for a list of commonly used
functions/ variables names, but it is functions
not practical to do so.

11

Appendix A

##  Appendix A presents a quick guide to commands and

functions used in the textbook.

Appendix A.

12

6
Spring 2015

## Operator MATLAB Example

 See Table 1.1-1 for more
information on operators.  + 5 + 4 = 9

 - 5 - 4 = 1
 See Table 1.1-2 for the
order of precedence.  * 5 * 4 = 20

 / 5 / 4 = 1.25

13

##  The = sign in Matlab is called the >> x=2

assignment operator. When you
type x=2, you are assigning the x =
value 2 to the variable x.
2

##  In Matlab, it is however also >> x=x+2

possible to type x=x+2. This tells
Matlab to add the value 2 to the x =
current value of x, replacing the old
4
value of x and making the most
recent value of x=4. >>

14

7
Spring 2015

Example 1.1-1

 Volume of a circular
>> r=8;
cylinder:
>> h=15;
 Given radius r and >> V=pi*r^2*h;
height h and volume >> V=V+0.2*V;
V=pi*r^2*h of a cylinder, >> r=sqrt(V/(pi*h))
cylinder with the same r =
height and a volume
8.7636
20% greater.
 Notice: Using a semicolon >>
“;” after a command
removes screen printing. Notice that new values
of r and V replace old values
15

##  Variable names must begin with a letter and must

contain less than 32 characters.
e.g. speed, distance, temp_1, etc…
 Remember: Matlab is case-sensitive.

##  Table 1.1-3 summarizes some commands and special

symbols for managing the work session: e.g. clc,
clear, quit, exist(‘name’), who, etc…

16

8
Spring 2015

## 1.1 Managing the Work Session

 Instead of retyping the entire line, press the up-arrow () and the
down-arrow () to recall previous commands you typed in your
session.

##  Notice that commands are stored in the Command History Window.

Double-clicking on a command in the command history window
recalls this command automatically.

##  If you go to Edit/Clear Command History, all previous commands

will be deleted (and can’t be recalled anymore)

17

##  Pressing tab while typing  auto

completes commands.
 Some useful commands:
 clear: clears all previous variables
 clear var1 var2: clears variables
var1 and var2.
 exist(‘var1’): checks if variable
var1 exist (returns 1 or 0)
 clc: clears screen
 who: lists all variables
 who var1 var2: lists var1 and var2
if they exist.
the letter A.
 whos: lists the variable names and their
sizes
18

9
Spring 2015

## 1.1 Predefined Constants

 Table 1.1-4: Special variables and constants
 Examples
 pi represents the number  
 Inf represents Infinity (number/0)
 NaN indicates an undefined numerical result (0/0)
 i,j represent the square root of –1,
necessary for complex numbers. Example
5+2i or 5+2j can be typed directly in Matlab.
 etc…

19

## 1.1 Complex Number Operation

>> s=3+7i;
>> w=5-9i;
>> w+s
 Matlab handles complex ans =
number algebra
8.0000 - 2.0000i
automatically. For example
>> w*s
c1= 1-2i (or 1-2*i).
ans =
 Caution: You CANNOT 78.0000 + 8.0000i
type 1-i2. >> w/s

ans =

-0.8276 - 1.0690i

>> (-3+7i)*(-3-7i)

ans =

58

20 >>

10
Spring 2015

##  Table 1.1-5: Numeric display formats

Examples:
 format short Four decimal digits
 format long 16 digits
 format short e Five digits plus exponent
 etc…

21

##  Check out the Menu bar and the Shortcut Toolbar in

Matlab
 Notice: Depending which Window is selected, the Menu
Bar changes accordingly.

22

11
Spring 2015

## 1.3 Computing with Matlab Arrays

>> x=[0 1 2 3]
 Matlab can handle collections of
numbers, called arrays, as if they x =
were a single variable.
0 1 2 3

>> x=[0,1,2,3]
 Possible way to define an array
elements must be separated by a x =
comma or space (or both). 0 1 2 3

>>
 Order of elements is important.

23

1.3 Arrays
>> x=2:8

 It is not necessary to x =

## type all the numbers in 2 3 4 5

the array if they are 6 7 8

##  The use of colon x =

indicates the spacing 2 3 4 5
and the length of the 6 7 8
array (only for real >> x=2:2:8
scalars).
x =
 By default, the spacing
2 4 6 8
 is 1.
>>

24

12
Spring 2015

## 1.3 Array Operations

 Simple array operations can be done like matrix operations:
>> x=0:3;
>> y=sin(x)

y =
0 0.8415 0.9093 0.1411 Note: Matlab
>> z=cos(x) trigonometric
functions use
z =
Using degrees can
1.0000 0.5403 -0.4161 -0.9900 be done by hand:
>> y+z cosine 60° is
cos(60*pi/180)
ans =

>>
25

1.3 Arrays

##  Array operations are done in Matlab mathematically correct. For

example, A*B results in a correct matrix multiplication, and not in an
element by element multiplication.

##  However, Matlab enables also element by element operations. A dot

“.” before the operator must be used for that purpose.
 Examples:
 A.*B results in an element by element multiplication.
 Also, exponentiation and division operators must have a dot:
A.^2 results in squaring the single elements of the array A, and
A./B results in an element by element division.

26

13
Spring 2015

1.3 Arrays
>> x=0:3;
>> y=sin(x)

y =

>> z=cos(x)

z =

>> y.^2+z.^2

ans =

## 1.0000 1.0000 1.0000 1.0000

>> y^2+z^2
??? Error using ==> mpower
Matrix must be square.

>>
27

##  You can see several values of an array by typing the

location or index of the value as follows:
>> x=-5:0.1:10;
>> x=-5:0.1:10;
>> x(151)
>> x(1)
ans =
ans =
10
-5
>> x(200)
??? Index exceeds matrix dimensions.
>> x(7)
>> x(0)
ans =
??? Subscript indices must either be real positive
integers or logicals.
-4.4000
>>
>>

28

14
Spring 2015

length command

## >> x=0:0.1:10; Note: for the index, we can use:

>> length(x) x(1), x(2), …
or
ans = x(1,1), x(1,2), …

## 101 length actually computes either the

number of elements of an array if the array
>> is a line vector, or the largest value of m or n
if the array is an mxn matrix.

29

## 1.3 mxn Arrays

 One way to write an mxn array in Matlab, use semicolons “;” to
separate between rows: >> A=[1;3;5]
>> A=[1 2 4 5;5 -3 9 2]
A =
A =
1
1 2 4 5 3
5 -3 9 2 5

## >> size(A) Here use >> A=[1+i;3i;2]

size(A)to
ans = A =
know array
2 4 dimension 1.0000 + 1.0000i
Index: mxn 0 + 3.0000i
2.0000
A= A(1,1) A(1,2)… >> length(A)
A(2,1) A(2,2)… ans = >> A=[1,2,4;2,4,5]

4 A =

1 2 4
30 2 4 5

15
Spring 2015

##  A polynomial can be described in Matlab >> roots([1,-7,40,-34])

with an array whose elements are the
ans =
polynomial coefficients, starting with the
coefficient with the highest power of x. 3.0000 + 5.0000i
 Use the roots command to solve for 3.0000 - 5.0000i
roots 1.0000

##  Example: f(x) = 1x3  7x2 + 40x  34 = 0 >> poly([1,3-5i,3+5i])

ans =
 To find the polynomial from its roots, use
the function poly([root1,root2,…]) 1 -7 40 -34

>>

31

##  There are several types of files that enables you to save

programs, data, and session results. Most importantly
are:
 MAT-files
 M-files

32

16
Spring 2015

1.3 MAT-files

##  If you want to stop using Matlab but continue the session

at a later time, you must use the save and load
commands.

##  Typing save causes Matlab to save the workspace

variables in a file called matlab.mat.

##  Typing load at a later time loads the variables that were

saved in the file matlab.mat.

33

1.3 MAT-files
 You can define your own MAT-file by using
 save filename and load filename
 The variables are then stored in the file filename.mat

##  You can save only certain variables by using

 Save filename var1 var2

##  Caution: If variables already exist in the workspace, they

are overwritten with the values of the variables from the
file filename.mat or matlab.mat.

34

17
Spring 2015

1.3 M-files

##  To save a sequence of commands

for later use, commands can be
written in a script file called M-file.
 Go to File/New/M-file
 A text editor/debugger will open
where you can write your
commands just like in the
command window.

##  Note: You can use any other text

editor to write your M-file, but the
Matlab editor has more practical
options.

35

##  It is important to know the location of the files you use

within Matlab. To open the files easily in Matlab, they
should be saved in a directory within Matlab’s “search
path”.
 To know if the directory is in the search path, type path
 To add or remove a directory from the search path, type
pathtool. This will take you to another path-setting
dialog-box

36

18
Spring 2015

##  If an M-file is saved in a directory within the search path

name in the command window: filename

##  To open an M-file, you can type open filename, or go

to File/Open and choose it.

37

##  Table 1.3-2 System, directory, and file commands

Examples
 dir lists all files in the current directory
 pwd displays the current directory
 pathtool starts the set path tool
 what lists all Matlab specific files (like MAT-
files) in the current directory
 etc…

38

19
Spring 2015

##  Matlab contains many powerful functions for easily

creating plots of different types, such as rectilinear,
logarithmic, surface, and contour plots.

##  Steps to make a simple plot

1. Define x-axes range (e.g. x=[0:0.1:10])
2. Define y=f(x) (e.g. y=sin(x))
3. Type plot(x,y)

>> x=0:0.1:10;
>> y=sin(x);
>> plot(x,y)
39

##  The plot appears

on the screen in a
graphical window,
named
Figure1.fig,
which is a Matlab
file.

40

20
Spring 2015

## 1.3 Plotting with Matlab

 This Figure1.fig
file can be saved
under a different
name and format
for usage within
other programs
like MS Word.

41

##  Table 1.3-3 Some Matlab plotting commands

Examples:
 grid puts grid lines on the plot
 title(‘text’) puts text in a title at the top of
the plot
 xlabel(‘text’) adds a text label to the x-axis
 ylabel(‘text’) adds a text label to the y-axix
 etc…

 Example:
plot(x,y),xlabel(‘time(s)’),ylabel(‘voltage(V)’),title(‘V vs. t’)

42

21
Spring 2015

## 1.3 Plotting with Matlab

 You can create multiple plots by including another set of values in the plot:
plot(x,y1,x,y2,x,y3)

##  The function [x,y]=ginput(n), gets n points and returns the x and y

coordinates in the vectors x and y which have a length n. For example,
plot(x,y),[x,y]=ginput(2)

 Typing plot(x,y,’+’) will return a scatter plot without a line, where the
data points are represented by a “+” sign.

##  Typing plot(x,y,’+-’) will return a scatter plot with data points

represented with + and connected by a line. (or plot(x,y,x,y,’+’))

##  loglog(x,y), semilogx(x,y), and semilogy(x,y) creates

logarithmic plots. (see Appendix A for more special plot functions)
43

##  We can solve simultaneous linear equation in Matlab

very easily using matrices. For example solving the
linear equation system:
6x + 12y + 4z = 70
7x – 2y + 3z = 5
2x + 8y – 9z = 64
>> A=[6,12,4;7,-2,3;2,8,-9];
>> B=[70;5;64];
>> Solution=A\B

Solution =

3
5
44 -2

22
Spring 2015

1.3 Statistics

##  Matlab has number of useful statistical functions (not all

built-in) like mean, median, mode, std, var, min,
max…that work on vectors.
>> x=0:10; >> x=0:10;
>> min(x) >> mean(x)

ans = ans =

0 5

ans = ans =

10 3.3166

45

## 1.4 Script Files and Editor/Debugger

Effective Use ofScript Files

 % is used to write
compiled). Text color in M-
file editor after % is green.
 Semicolons “;” can be
used as usual.
 Filenames can be typed
directly in the command
window, if their directory is
in the search path.
 Writing type filename
in the command editor
displays the file in the See page 31-32 in TB on what to
command window. remember when using script files
46

23
Spring 2015

##  Debugging means finding program “Bugs” or errors:

 Syntax errors: e.g. missing parenthesis or comma, …
 Runtime errors: e.g. dividing by zero,…
 Syntax errors are usually found by Matlab, and program will not run
until error is corrected. Runtime errors are however harder to locate.

##  To run an M-file, file has first to be saved.

 To run and save automatically from editor:
 Press F5
 Go to Debug/Save and Run

 If due to a certain mistake, you would like to stop the program from
running, press
Ctrl+c
47

##  Table 1.4-2 Input/Output commands

Examples
 disp(A) displays content, but not
the name of an array A.
 disp(‘text’) displays text string
enclosed in quotes.
 x = input(‘text’) displays text in quotes
imp
and waits for user to
 etc… input value for x.
 Example: T4.1-2
48

24
Spring 2015

##  In the command window, you can type:

 help funcname
 lookfor funcname
 doc funcname
 etc…

49

##  Table 1.6-1 Relational Operators

< less than
 <= less than or equal
> greater than
 >= greater than or equal
 == Equal to
 ~= Not equal to

##  The result is either 1 (for true) or 0 (for false).

 This result can be used as a logical variable.
50

25
Spring 2015

##  With the relational operators, we can directly compare

variables: >> x=1;
>> y=2;
>> x==y

ans =

>> x='m';
>> y='m';
>> x==y

ans =

>>
51

## 1.6 Relational Operators

 We can compare arrays on an element-by-element basis:
>> x=[6,3,9]; >> A=[1,2,3;4,5,6];
>> y=[14,2,9]; >> B=[1,2,3;5,5,6];
>> z=(x<y) >> A==B

z = ans =

1 0 0 1 1 1
0 1 1
>> z=(x==y)
>> C=A~=B
z =
C =
0 0 1
0 0 0
>> z=x==y %another way to write it 1 0 0

z = >>

0 0 1

52

26
Spring 2015

##  Relational operators can also be used within arguments. For example

writing x(x<y) returns the elements of the array x which are less than y.

>> x=[2,3,1];
>> y=[1,2,5];
>> x(x>y)

ans =

2 3

>>

53

##  The find function: finds the NONZERO elements in an

array.
 Returns the indices not the element values
 This is useful when writing decision-making programs.

>> x=[1,2,9,0,3,0,3];
>> y=find(x)

y =
Only
1 2 3 5 7 indices are
returned.

54

27
Spring 2015

##  Conditional statements allow us to write programs that make

decisions.
 We should pay attention to the order of expressions.
 We can write nested IFs by using the elseif statement.
 Syntax If expression
commands
elseif expression
If expression commands
commands elseif expression
else commands
commands …
end else
commands
55 end

##  Example: Write a program in Matlab to compute y(x) for

15 4x 10 if x  9

y(x)   10x 10 if 0  x  9
 10
 if x  0

56

28
Spring 2015

##  Example: Write a program in Matlab to compute y(x) for

15 4x 10 if x  9

y(x)   10x 10 if 0  x  9
 10
 if x  0
%ifexample: Evaluation of y(x)
x=input('Enter the value of x: '); >> ifexample
if x>=9 Enter the value of x: 2
y=15*sqrt(4*x)+10
elseif x>=0 y =
y=10*x+10
else 30
y=10
end >>

57

1.6 Loops

##  A loop is a structure for repeating a calculation an

number of times. There are two types of loops:

##  while loop: used when the looping process must

terminate when a specified condition is satisfied, and
thus the number of executions is not known in

58

29
Spring 2015

1.6 Loops

 Syntax:

## for expression while expression

commands commands
end end

59

##  Table 1.6-2 Some Matlab programming statements

Examples:
 else Delineates an alternate block of
commands.
 if Executes commands conditionally
 etc…

60

30
Spring 2015

1.6 Loops

 for-loop example:
%first method %second method
m=0; m=1;
x(1)=10; x(m)=10;
for k=[2:3:11] for k=2:3:11
m=m+1; x(m+1)=x(m)+k^2;
x(m+1)=x(m)+k^2; m=m+1;
end end
x x

>> x

x =

10 14 39 103 224
61

1.6 Loops

 while-loop example:

clear
x=5;
k=0; y =
while x<25
k=k+1; 15 27 51
y(k)=3*x;
x=2*x-1; >>
end
y

62

31
Spring 2015

## 1.6 Example 1.6-2

15 4x 10 if x  9

y(x)   10x 10 if 0  x  9
 10
 if x  0

63

## 1.6 Example 1.6-2

15 4x 10 if x  9

y(x)   10x 10 if 0  x  9
 10
Plot y(x) vs x for -5x30  if x  0
%Example 1.6-2: using for loop %Example 1.6-2: using while loop
clear clear
dx=35/300; dx=35/300;
x=[-5:dx:30]; x=[-5:dx:30];
k=1;
for k=1:length(x)
if x(k)>=9 while k<=length(x)
y(k)=15*sqrt(4*x(k))+10;
elseif x(k)>=0 if x(k)<0
y(k)=10*x(k)+10; y(k)=10;
else elseif (x(k)>=0)&&(x(k)<9)
y(k)=10; y(k)=10*x(k)+10;
end else
end y(k)=15*sqrt(4*x(k))+10;
plot(x,y),xlabel('x'),ylabel('y') end

k=k+1;
end
64 plot(x,y),xlabel('x'),ylabel('y')

32
Spring 2015

## 1.6 Example 1.6-3

 Compute sum of the 1st 15 terms in the series 5k 2-2k, for
k=1,2,…,15

65

## 1.6 Example 1.6-3

 Compute sum of the 1st 15 terms in the series 5k 2-2k, for
k=1,2,…,15
%Example 1.6-3: using for loop (TB) %Example 1.6-3: using the sum function
clear clear
total=0; k=1:15;
for k=1:15; y=5*(k.^2)-2*k;
total = 5*(k^2)-2*k + total;
end total2=sum(y)
total %it sums over all ys, i.e y(1)to y(15)

%Example 1.6-3: using for loop %Example 1.6-3: using while loop
clear clear
total1=0; total3=0;
k=1:15; k=1:15;
y=5*(k.^2)-2*k; y=5*(k.^2)-2*k;

## for h=1:15 h=1;

total1 = total1 + y(h); while h<=15
end total3 = total3 + y(h);
total1 h=h+1;
end
66 total3

33
Spring 2015

## 1.6 Example 1.6-4

 Find how many terms it’s required for the sum of the series 5k2-2k,
for k=1,2,…to exceed 10000. What’s the sum of these many terms?

67

## 1.6 Example 1.6-4

 Find how many terms it’s required for the sum of the series 5k2-2k,
for k=1,2,…to exceed 10000. What’s the sum of these many terms?

## k=0; >> Example_1_6_4

total=0; the number of terms is:
while total<=1e4 18
k=k+1;
total=5*k^2-2*k+total; the sum is:
end 10203
disp('the number of terms is:')
disp(k)
disp('the sum is:')
disp(total)

68

34
Spring 2015

## 1.6 Example 1.6-5

 Determine how long it will take to accumulate at least \$10000 in a
bank account if you deposit \$500 initially and 500\$ at the end of
each year, if the account pays 5% annual interest

69

## 1.6 Example 1.6-5

 Determine how long it will take to accumulate at least \$10000 in a
bank account if you deposit \$500 initially and 500\$ at the end of
each year, if the account pays 5% annual interest

%Example 6.1-5
clear
>> Example_1_6_5
amount=500;
years=0;
amount =
while amount<1e4
1.0789e+004
amount=amount*1.05+500;
%or amount=amount+500+amount*0.05
years=years+1;
end years =
amount
years 14

70

35