Vous êtes sur la page 1sur 60

CS101 Computer Systems 1

Chathura De Silva, Dept. of Computer Science and Engineering


CS-101: Computer Systems
Introduction to programming
using MatLab
Lecture 1
CS428 Introduction to prg. Using MatLab 2
Chathura De Silva, Dept. of Computer Science and Engineering
CS428 Introduction to prg. Using MatLab 3
Chathura De Silva, Dept. of Computer Science and Engineering
Introduction to MATLAB
What is MATLAB?
n Short for MATrix LABoratory
n Capable of solving any technical problems
n A Special-purpose, interpreter-based, computer
application for technical computing, simulation,
engineering and scientific computing, numerical
computation and visualization.
n May be used without intensive programming knowledge.
n MATLAB computing environment Widely used for
scientific and engineering.
n Developed and marketed by a company called MathWorks
(http://www.mathworks.com).
CS428 Introduction to prg. Using MatLab 4
Chathura De Silva, Dept. of Computer Science and Engineering
Introduction to MATLAB (continue)
The Advantage of MATLAB
n Ease of Use
n Platform Independence
n A large collection of predefined functions
n Arranged into toolboxes for different deciplines.
n Device-Independent Plotting
n Graphical User Interface
n MATLAB Compiler
Disadvantages of MATLAB
n Interpreted language slow
n Cost
n Not for symbolic manipulations
CS428 Introduction to prg. Using MatLab 5
Chathura De Silva, Dept. of Computer Science and Engineering
Introduction to MATLAB(continue)
The MATLAB Environment includes
n Graphical user interface
n MATLAB desktop and Command Window
n A command history
n An editor and debugger, and
n A Browser for viewing help, the workspace, files, and
the search path.
CS428 Introduction to prg. Using MatLab 6
Chathura De Silva, Dept. of Computer Science and Engineering
Introduction to MATLAB(continue)
n MATLAB Desktop the main interface for working with
MATLAB
CS428 Introduction to prg. Using MatLab 7
Chathura De Silva, Dept. of Computer Science and Engineering
Introduction to MATLAB(continue)
n MatLab could be used in two different modes
n Command Mode (Interactive Mode)
n Similar to a scientific calculator (but with lot more
features).
n Input a single operation (i.e. mathematical
expression) and results are displayed
immediately.
n Programmed Mode (Scripting Mode)
n Like a programmable calculator (but can
accommodate very large programs).
n Define sequences of operations involving
variables and functions.
CS428 Introduction to prg. Using MatLab 8
Chathura De Silva, Dept. of Computer Science and Engineering
MATLAB Electrical Calculator:
An Interactive Session
n Start MATLAB
n Example1: Enter the
following lines on the
MATLAB Command
Windows
>> watt = 100;
>> volt = 220;
>> i = watt/volt
i =
0.4545
n Double Click the Command
in the Command History
Window
Workspace
Command
Window
Command
History
CS428 Introduction to prg. Using MatLab 9
Chathura De Silva, Dept. of Computer Science and Engineering
MATLAB Electrical Calculator:
an Interactive Session(continue)
n Example 2: Calculate the area of a circle with a
radius of 0.001 inch (p r
2
).
>> pi
ans =
3.1416
>> area = pi*0.001^2
area =
3.1416e-006
>>
CS428 Introduction to prg. Using MatLab 10
Chathura De Silva, Dept. of Computer Science and Engineering
MATLAB: an Interactive Session
n Example 3: Sum of 12 numbers with continue statement
on successive lines by typing an ellipsis () at the end of
the first line
>> x = 1 + 2+3+4+5+6+7+8+9+10+11+12
x =
78
>> x = 1 + 2 + 3 + 4 + ...
5 + 6 + 7 + 8 + 9 + 10 + 11 + 12
x =
78
CS428 Introduction to prg. Using MatLab 11
Chathura De Silva, Dept. of Computer Science and Engineering
Using Constants and Variables
n Like in algebra, we can use symbols (i.e. Identifiers
or Variables) to represent unknown quantities.
2
2 3 5 y x x = + +
n Result of the expression (i.e. value assigned to
variable y) depends on the value of x.
n On symbolic arithmetic point of view, y can be defined
in terms of x. However on numerical terms, without a
value assigned for x, y remains undefined.
n In MatLab, an expression can be evaluated only if all
variables in the right-hand side are assigned with
values.
CS428 Introduction to prg. Using MatLab 12
Chathura De Silva, Dept. of Computer Science and Engineering
Using Constants and Variables
n Constants: sum of resistance
(ohms)
n 100 + 120
n Variables: sum of resistance
n R1 + R2 + 0.01
CS428 Introduction to prg. Using MatLab 13
Chathura De Silva, Dept. of Computer Science and Engineering
Constants and Variables(cont.)
n MATLAB Sum Calculator: enter the following lines
at the MATLAB command window:
>> 100 + 120
ans = 220
>> Rt = 100 + 120
Rt = 220
>> R1 = 100;
>> R2 = 120;
>> R1 + R2 + 0.01
ans = 220.01
CS428 Introduction to prg. Using MatLab 14
Chathura De Silva, Dept. of Computer Science and Engineering
Constants and Variables(cont.)
MATLAB Variables and Assignments
n No need to declare MATLAB variables before they are used.
Assigns a value to a variable creates the variable.
n Variable names must begin with a letter, which may be
followed by any combination of letters, digits, and
underscores.
n Case Sensitive, so A and a are not the same variable.
n The variable on the right-hand side of the assignment must
has a value.
n A variables value is over written if it already exists.
CS428 Introduction to prg. Using MatLab 15
Chathura De Silva, Dept. of Computer Science and Engineering
Constants and Variables in MatLab
n As the name implies (MATrix LABoratory), MatLab
treats each and every variable as a Matrix.
n Thus scalar values are treated as special case
matrices, a 1x1 dimension matrix.
n Constants are also like variables, except their values
will never change.
n There are some pre-defined constants which cannot
be changed.
CS428 Introduction to prg. Using MatLab 16
Chathura De Silva, Dept. of Computer Science and Engineering
Constants and Variables (cont.)
n Natural Numbers: counting numbers) =
{1, 2, 3, 4, 5, 6, } (will go till infinity, but practical
sequences will always have a limit)
n In MatLab a number sequence can be represented as
follows
<start>:<step_size>:<end>
n MATLAB row vector commands
>> x = 1: 1: 10
or
>> x = 1:10
CS428 Introduction to prg. Using MatLab 17
Chathura De Silva, Dept. of Computer Science and Engineering
Constants and Variables (cont.)
n Whole Numbers: {0, 1, 2, 3, 4, 5, 6, }
n Add 0 to the whole numbers
n MATLAB Commands
>> x = [0, x]
or
>> clear x
>> x = 0:1:10
CS428 Introduction to prg. Using MatLab 18
Chathura De Silva, Dept. of Computer Science and Engineering
Constants and Variables(cont.)
n Integers: {, -3, -2, -1, 0, 1, 2, 3, }
n Combining whole
numbers and
negatives of the
whole numbers
n MATLAB Commands
>> y = -3:3
y =
-3 -2 -1 0 1 2 3
CS428 Introduction to prg. Using MatLab 19
Chathura De Silva, Dept. of Computer Science and Engineering
Constants and Variables(cont.)
n Some Predefined MATLAB
Variables
n ans holds the value of the
most recent calculation result
n pi p
(Circumference/Diameter), ratio
of the circumference of a circle
to its diameter; pi = 3.1415926

n eps - Smallest number such that


when added to 1 create a
floating-point number greater
than 1; eps = 2.2204e-016.
n inf - Positive infinity, generated
through divided by zero, such as
1/0
CS428 Introduction to prg. Using MatLab 20
Chathura De Silva, Dept. of Computer Science and Engineering
( ) ( )( )
2 2 2 2
2
1 2
x x x x
x x x x x x x
x x
=
= +
=
=
CS428 Introduction to prg. Using MatLab 21
Chathura De Silva, Dept. of Computer Science and Engineering
Constants and Variables(cont.)
n Some Predefined MATLAB
Variables
n NaN - Not a number,
obtained from invalid
operations such as 0/0,
inf/inf, and so on.
n realmax - Largest positive
floating point number;
realmax = 2.2251e308.
n realmin - Smallest
positive floating point
number; realmin = 2.2251e-
308.
CS428 Introduction to prg. Using MatLab 22
Chathura De Silva, Dept. of Computer Science and Engineering
Constants and Variables(cont.)
n Some Prefixes for SI
Units (International
Standard)
micro 10
-6
n nano 10
-9
p pico 10
-12
f femto 10
-15
a atto 10
-18
z zepto 10
-21
y yocto 10
-24
Abbreviat
ion
Prefix Power
CS428 Introduction to prg. Using MatLab 23
Chathura De Silva, Dept. of Computer Science and Engineering
Constants and Variables
n Some Prefixes for SI Units
(International Standard)
G giga 10
9
M mega 10
6
k kilo 10
3
da deka 10
1
d deci 10
-1
c centi 10
-2
m milli 10
-3
Abbreviat
ion
Prefix Power
Source: http://www.frontierusa.com/
CS428 Introduction to prg. Using MatLab 24
Chathura De Silva, Dept. of Computer Science and Engineering
Constants and Variables
n Some Prefixes for SI Units (International Standard)
Y Yotta 10
24
Z Zetta 10
21
E exa 10
18
P peta 10
15
T tera 10
12
Abbreviation Prefix Power
CS428 Introduction to prg. Using MatLab 25
Chathura De Silva, Dept. of Computer Science and Engineering
MATLAB Math. Operators
Operators
+ op1 + op2 Adds op1 and op2
- op1 op2 Subtract op2 from op1
* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divide op1 by op2
^ op1 ^ op2 Computes the power op1 goes
to the power of op2
CS428 Introduction to prg. Using MatLab 26
Chathura De Silva, Dept. of Computer Science and Engineering
MATLAB Math. Operators (cont.)
n Arithmetic Expressions
n velocity = distance / time;
n force = mass * acceleration;
n count = count + 1;
n power = V^2/R;
CS428 Introduction to prg. Using MatLab 27
Chathura De Silva, Dept. of Computer Science and Engineering
MATLAB Math. Operators
n Example 2-1: Mr. A rides a bike 140 meters in 20
second. What is the average speed of bike riding?
n MATLAB Solution
>> v = 140/20
v =
7
CS428 Introduction to prg. Using MatLab 28
Chathura De Silva, Dept. of Computer Science and Engineering
MATLAB Math. Operators (cont.)
n Example 2-2: Neglecting friction and air resistance, what
force is required to accelerate an automobile weighting
2000 lbs from 30.0 miles/hr to 55.0 miles/hr in 10.0
second.
MATLAB Solution
>>% acceleration a = vf v1/ dt
% force = ma (comments)
>> m = 2000;
>> a = (55.0 - 30.0)/(10/3600);
>> f = m*a
f =
18000000
CS428 Introduction to prg. Using MatLab 29
Chathura De Silva, Dept. of Computer Science and Engineering
MATLAB Math. Operators (cont.)
n Example 2-3: Electric Power Calculation, for R = 15
ohms, voltage = 120 volts: P = V^2 /R (watts).
MATLAB Solution:
>>R = 15.0;
>>V = 120;
>>P = V^2 / R
P =
960
CS428 Introduction to prg. Using MatLab 30
Chathura De Silva, Dept. of Computer Science and Engineering
Writing and Evaluating Math.
Equations in MATLAB Operators (cont.)
Example 2-4: The sum of three consecutive numbers is 93.
Find the numbers.
Solution:
Step 1: Represent unknown quantities as variables
Let x be the consecutive number
Let x + 1 be the second consecutive number
Let x + 2 be the third consecutive number
Step 2: Write the equation
x + (x + 1) + (x + 2) = 93
Step 3: Solve x
3x + 3 = 93
3x = 90
x = 30
CS428 Introduction to prg. Using MatLab 31
Chathura De Silva, Dept. of Computer Science and Engineering
Writing and Evaluating Math.
Equations in MATLAB Operators (cont.)
Example 2-4: The sum of three consecutive numbers is
93. Find the numbers.
Solution:
Step 4; Using the equation in Step 2 and MATLAB
command to verify the answer.
>> x = 30;
>> x + (x +1) + (x +2)
>> ans
= 93
CS428 Introduction to prg. Using MatLab 32
Chathura De Silva, Dept. of Computer Science and Engineering
Writing and Evaluating Math.
Equations in MATLAB Operators (cont.)
Example 2-5: There are two ICs on a circuit board, one called
IC1 and another called IC2. There is an average operating
temperature of 65C. What is the operating temperature of
each IC if the IC2 has a 10C lower operating temperature
than IC1?
Solution:
Step 1: Write the equations:
(1) --- Taveg = (T1 + T2)/2 = 65;
(2) --- T1 T2 = 10;
Step 2: Solve the equations
Rewrite equation (2) as equation (3) T1 = 10 + T2
Substitute (3) into (1)
Taveg = (10+T2+T2)/2 = 65
10 + 2T2 = 130
2T2 = 120
T2 = 60C
Now, we substitute T2 into (2) to solve
T1 = 10 + T2 = 70C
CS428 Introduction to prg. Using MatLab 33
Chathura De Silva, Dept. of Computer Science and Engineering
Writing and Evaluating Math.
Equations in MATLAB Operators (cont.)
Example 2-5:
Step 3: Verify the solution using MATLAB
>> T1 = 70;
>> T2 = 60;
>> (T1 + T2)/2
ans
= 65
>> T1 T2
ans
= 10
CS428 Introduction to prg. Using MatLab 34
Chathura De Silva, Dept. of Computer Science and Engineering
Example 2-6: Graph the line
y = a x + b, where b is
called the offset (b = 0), a
is called the slope (a = 3),
and x is in the following
range: -20 x 20.
Solution:
n Need several steps.
n We will later se how we
can automate these
command sequences
using a script file
Writing and Evaluating Math.
Equations in MATLAB Operators (cont.)
CS428 Introduction to prg. Using MatLab 35
Chathura De Silva, Dept. of Computer Science and Engineering
Writing and Evaluating Math.
Equations in MATLAB Operators (cont.)
CS428 Introduction to prg. Using MatLab 36
Chathura De Silva, Dept. of Computer Science and Engineering
MatLab Desktop Environment
CS428 Introduction to prg. Using MatLab 37
Chathura De Silva, Dept. of Computer Science and Engineering
Desktop Tools
Started MATLAB and see the three sub-windows:
n Command Window
n Current Directory
n Command History
At the command
window, we enter
>>help help
CS428 Introduction to prg. Using MatLab 38
Chathura De Silva, Dept. of Computer Science and Engineering
Command Window
n Running Functions
n Entering Variables
n Controlling Input/Output
n Searching Items
n Running Programs
n Setting Preferences for the Command
Window
CS428 Introduction to prg. Using MatLab 39
Chathura De Silva, Dept. of Computer Science and Engineering
Running Commands
An Example:
>> magic(3)
ans =
8 1 6
3 5 7
4 9 2
>> help magic >> help magic
MAGIC MAGIC Magic Magic square. square.
MAGIC(N) is an N MAGIC(N) is an N- -by by- -N N
matrix constructed from the matrix constructed from the
integers integers
1 through N^2 with equal 1 through N^2 with equal
row, column, and diagonal row, column, and diagonal
sums. sums.
Produces valid magic Produces valid magic
squares for all N > 0 except N squares for all N > 0 except N
= 2. = 2.
15
15
15
15
15
15 15 15
CS428 Introduction to prg. Using MatLab 40
Chathura De Silva, Dept. of Computer Science and Engineering
Entering Variables
>> x = 10
x = 10
>> y = 10
y = 10
>> x * y
ans = 100
>> x / y
ans = 1
>> x + y
ans = 20
>> x - y
ans = 0
>>
CS428 Introduction to prg. Using MatLab 41
Chathura De Silva, Dept. of Computer Science and Engineering
Controlling Input/Output
Format Function control the display formats
for numeric values
n Examples
>> x = 1/3
x = 0.3333
>> y = 1.2345e-7
y = 1.2345e-7
>> format short e
>> x
x = 3.3333e-001
>> y
y = 1.2345e-007
Hit Enter key Hit Enter key
MATLAB Displays MATLAB Displays
Hit Enter key Hit Enter key
MATLAB Displays MATLAB Displays
Hit Enter key Hit Enter key
Enter x Enter x
Enter y Enter y
MATLAB Echoes MATLAB Echoes
CS428 Introduction to prg. Using MatLab 42
Chathura De Silva, Dept. of Computer Science and Engineering
Controlling Input/Output (continue)
n Format Function:
>> help format
FORMAT Set output format.
All computations in MATLAB are done in double
precision.
FORMAT may be used to switch between
different output
display formats as follows:
FORMAT Default. Same as SHORT.
FORMAT SHORT Scaled fixed point format
with 5 digits.
FORMAT LONG Scaled fixed point format
with 15 digits.
FORMAT SHORT E Floating point format with
5 digits.
FORMAT LONG E Floating point format with
15 digits.
>> format long
>> x
x =
0.33333333333333
>> y
y =
1.234500000000000e-
007
CS428 Introduction to prg. Using MatLab 43
Chathura De Silva, Dept. of Computer Science and Engineering
Controlling Input/Output (continue)
n Format Function:
>> help format
FORMAT SHORT G Best of fixed or floating
point format with 5 digits.
FORMAT LONG G Best of fixed or floating
point format with 15 digits.
FORMAT HEX Hexadecimal format.
FORMAT + The symbols +, - and blank
are printed for positive, negative and zero
elements. Imaginary parts are ignored.
FORMAT BANK Fixed format for dollars
and cents.
FORMAT RAT Approximation by ratio of
small integers.
>> format long g
>> x
x =
0.333333333333333
>> y
y = 1.2345e-007
>> format bank
>> x
x = 0.33
>> y
y = 0.00
>> format rat
>> x
x = 1/3
>> y
y = 1/8100446
CS428 Introduction to prg. Using MatLab 44
Chathura De Silva, Dept. of Computer Science and Engineering
Controlling Input/Output (continue)
File File - -> Preferences > Preferences
Allows you to set Allows you to set
up various up various
numeric display numeric display
formats through formats through
GUI GUI
CS428 Introduction to prg. Using MatLab 45
Chathura De Silva, Dept. of Computer Science and Engineering
Suppress Output
n Suppressing Output
n End of the statement with a semicolon
n Increase statement and program
execution speed
n An Example
>> x = 10;
>> y = 10;
>> product = x * y
Product = 100
CS428 Introduction to prg. Using MatLab 46
Chathura De Silva, Dept. of Computer Science and Engineering
Entering long Statements
n If a statement does not fit on a line (too long),
uses an ellipsis (three periods), follow by
Enter or Return, to indicate the continuation of
the statement to the next line
n For an example
>> x = 1 + 2 + 3 + 5 + 6 + 7 + ...
8 + 9 + 10
x =
51
CS428 Introduction to prg. Using MatLab 47
Chathura De Silva, Dept. of Computer Science and Engineering
Command Line Editing and Command History
n Command Line Editing
Keys such as right arrow ? , down arrow ?, up
arrow ?, left arrow ? , etc, can be used to edit
commands
n Command History
n The entered commands at the Command
Windows are recorded or logged in the
Command History
n We can view previous commands or
statements
n We can copy or execute rerun previous
statements
CS428 Introduction to prg. Using MatLab 48
Chathura De Silva, Dept. of Computer Science and Engineering
The MATLAB Workspace
n who function
n whos function
n clear function
>> who
Your variables are:
x y
>> whos
Name Size Bytes Class
x 1x1 8 double array
y 1x1 8 double array
Grand total is 2 elements using 16 bytes
>> clear x
>> who
Your variables are:
y
>> clear
>> whos
CS428 Introduction to prg. Using MatLab 49
Chathura De Silva, Dept. of Computer Science and Engineering
The MATLAB Workspace
n save function
n load function
>> save 8_20_2004.mat
>> clear
>> whos
>> load 8_20_2004.mat
>> whos
Name Size Bytes Class
ans 1x1 8 double array
x 1x1 8 double array
y 1x1 8 double array
Grand total is 3 elements using 24 bytes
>> clear
>> whos
Current Directory
CS428 Introduction to prg. Using MatLab 50
Chathura De Silva, Dept. of Computer Science and Engineering
Save Command
n We can use help save to see documentation of
SAVE function and learn how to Save workspace
variables to disk.
n SAVE FILENAME saves all workspace variables
to the binary "MAT-file, If FILENAME has no
extension, .mat is assumed.
n SAVE, by itself, creates the binary "MAT-file"
named 'matlab.mat'. It is an error if 'matlab.mat'
is not writable.
n SAVE FILENAME X saves only X.
n SAVE FILENAME X Y Z saves X, Y, and Z. The
wildcard '*' can be used to save only those
variables that match a pattern.
CS428 Introduction to prg. Using MatLab 51
Chathura De Silva, Dept. of Computer Science and Engineering
Save Command (continue)
MATLAB also offers various saving options:
n ASCII Options:
n SAVE ... -ASCII uses 8-digit ASCII form instead
of binary regardless of file extension.
n SAVE ... -ASCII -DOUBLE uses 16-digit ASCII
form.
n SAVE ... -ASCII -TABS delimits with tabs.
n And more will be discussed later
CS428 Introduction to prg. Using MatLab 52
Chathura De Silva, Dept. of Computer Science and Engineering
Help Browser
CS428 Introduction to prg. Using MatLab 53
Chathura De Silva, Dept. of Computer Science and Engineering
Workspace Browser
CS428 Introduction to prg. Using MatLab 54
Chathura De Silva, Dept. of Computer Science and Engineering
Current Directory Browser
CS428 Introduction to prg. Using MatLab 55
Chathura De Silva, Dept. of Computer Science and Engineering
The Edit/Debug
n Use the Editor/Debugger to create and debug M-files, which are
programs you write to run MATLAB functions.
n The Editor/Debugger provides a graphical user interface for
basic text editing, as well as for M-file debugging.
CS428 Introduction to prg. Using MatLab 56
Chathura De Silva, Dept. of Computer Science and Engineering
The Edit/Debug (continue)
CS428 Introduction to prg. Using MatLab 57
Chathura De Silva, Dept. of Computer Science and Engineering
The Edit/Debug (continue)
Create a mlab_exs directory
Save the M-file as sine60hz.m
CS428 Introduction to prg. Using MatLab 58
Chathura De Silva, Dept. of Computer Science and Engineering
The Edit/Debug (continue)
CS428 Introduction to prg. Using MatLab 59
Chathura De Silva, Dept. of Computer Science and Engineering
Testing/Debugging sin60hz.m
Click -> Debug -> Run
CS428 Introduction to prg. Using MatLab 60
Chathura De Silva, Dept. of Computer Science and Engineering
Other Commands
n Other Useful MATLAB Management
Commands/Functions
n Demo - Run demos
n help - Online help
n ver - Current MATLAB and toolbox
versions
n version - Current MATLAB version
number
n path - MATLAB Search path
n diary - Save typed commands on a
named file

Vous aimerez peut-être aussi