Computer Programming
with MatLab
First Bytes Summer Camp
Mary Eberlein and Mike Scott
Using MatLab
1
Who am I?
•
•
•
•
•
From St. Charles, Missouri
Attended Stanford University 1986 - 1990
US Navy 1990 - 1998, Nuclear Submariner
Married 1997 to Kelly, A US Navy Nurse
Masters in CS, 1998, Rensselaer Polytechnic
Institute
• Out of Navy 1998, moved to Austin to work for
Motorola (Worst 10 weeks of my life)
• 2 years teaching CS at Round Rock High School
• 3 years as a lecturer here at UTCS department
Using MatLab
2
Using MatLab
3
Agenda
• Learn what computer programming is
• Learn how to do programming with another program
called MatLab
• Programming concepts today
–
–
–
–
–
mathematical expressions
variables, boxes that hold numbers
assignment, giving variables new values
matrices and arrays, larger more useful variables
functions, solving problems with mathematical
expressions, variables, and assignments
Using MatLab
4
What is Computer Programming?
• "Having surveyed the relationships of computer science with other
disciplines, it remains to answer the basic questions: What is the
central core of the subject? What is it that distinguishes it from the
separate subjects with which it is related? What is the linking thread
which gathers these disparate branches into a single discipline? My
answer to these questions is simple -- it is the art of programming a
computer. It is the art of designing efficient and elegant methods of
getting a computer to solve problems, theoretical or practical, small or
large, simple or complex. It is the art of translating this design into an
effective and accurate computer program."
– C.A.R. Hoare, Essays in Computing Science
• Many different areas of Computer Science, computer programming is
an important tool in almost all of those areas
Using MatLab
5
Algorithms and Computer Programs
• Algorithm, a set of detailed, exact instructions, to
carry out some task or solve some problem
• ACTIVITY: Create an algorithm to look up the phone
number for Papa John's Pizza in the yellow pages
• A computer program is the expression of an
algorithm in a language a computer can understand
• MatLab is a computer program that lets you write
other computer programs
Using MatLab
6
Starting MatLab
• Click the start button in the lower left
– select the programs folder
• select the MatLab folder
– select MatLab (It takes a while to start up.)
• MatLab starts
–
–
–
–
a window with three areas
Command Window
Command History
Workspace Browser
• Maximize the window
Using MatLab
7
Click this icon to maximize
Workspace
Browser
Command
Window
Command
History
Using MatLab
8
Simple MatLab Actions
• Put the cursor in the Command Window and click next to
the prompt. The prompt is the set of double greater than
symbols
>>
– type in 2 + 2 and press the Enter or Return key
– What happened?
Using MatLab
9
More Simple Actions
• Try these commands one at a time
2 + 10
2 - 10
2 * 3
1.5 * 3
10 / 3
2 ^ 3
2 8 3
• What happened?
• Trying pressing the up arrow once.
• Try several times.
Using MatLab
10
Is This Computer Programming?
• So what is the difference between MatLab and a
calculator?
– At this point not much
– You will write more complicated and involved
calculations, but at its very heart a computer is a lot like
a four function calculator
– The Big Difference is a computer can do calculations
really fast
• Pentium 4 chip from 2001 can perform approximately
1,700,000,000 computations per second
If something can be represented numerically it can be
stored on a computer and manipulated via the computer!
pictures, images, video, music, text, DNA data, …
Using MatLab
11
More MatLab
• Like a calculator and algebra MatLab has functions
• try this command
>> sqrt(16)
• What happened? What does sqrt do?
• MatLab has hundreds of built in functions
–
–
–
–
Appendix A of Learning MatLab 6.5
We will use only a few
We will also create our own functions
This is computer programming!!!
Using MatLab
12
Variables
• Try the following command
>> firstvar = 12
• what happened? Look in the Workspace Browser
section.
Using MatLab
13
Variables
• There is now an entry in the Workspace Browser for
firstvar and an icon for it
• Try the command
>> firstvar
• What happened?
• Double click on the icon for firstvar in the
Workspace Browser
Using MatLab
14
Variables
• A variable is a storage container
• The variable has a name, a type, and a current value
– The name of our this variable is firstvar
– The type of our firstvar is double array
– The current value of firstvar is 12
• The name of a variable cannot be changed
– Some languages allow the data type to be changed, some
do not. MatLab allows you to change the type
• The current value of a variable can be changed
– another fundamental concept of programming
• MatLab lets you look at the contents of a variable
– the window that opens when double clicking on the
firstvar icon
Using MatLab
15
Array Editor Window
Name
of Variable
Current Value
of Variable
Leave the Array Editor Window for firstvar open and back in
the Command Window try the following command
>> firstvar = 20
What happened?
Using MatLab
16
Manipulating Variables
• Try the following command
>> firstvar = firstvar + 1
• This is not a mathematical statement. It is a command!
– if it were a mathematical statement it would be false
• in many programming languages including MatLab the
equals symbol, = , means perform an assignment
• definition of assignment: evaluate the expression on the
right hand side of the equals sign and store the answer in
the variable on the left hand side of the equal sign
Using MatLab
17
Experiment with Assignment
• Some of these commands purposefully have errors
>>
>>
>>
>>
>>
>>
>>
>>
>>
firstvar
firstvar
firstvar
firstvar
firstvar
firstvar
firstvar
firstVAR
firstvar
=
=
=
=
=
=
+
=
=
2
firstvar + 2
firstvar * 2
firstvar * 2 + 2
firstvar + 2 * 2
(firstvar + 2) * 2
2 = firstvar
firstvar + 2
firstVar + 2
Using MatLab
18
More Variable Assignment
>>
>>
>>
>>
firstvar = 10
firstvar = firstvar - 100
secondvar = abs(firstvar)
thirdvar = firstvar * secondvar
• Some thing to notice
– firstvar and firstVAR are not the same thing, they are two
different, unique names
– the left hand side must be a single variable
– when a variable that has not been used yet is placed on the left
hand side the variable is created and can be seen in the
Workspace Browser
Using MatLab
19
Matrices - A More Complex Variable
• MatLab is designed to work with mathematical
matrices
• A mathematical matrix is a collection of numbers in a
rectangular arrangement
2
15
13
1
5
6
• Properties of the matrix include the number of rows
and columns
• A cell is specified by its row and column number
cell(1, 1) = 2
cell(1, 2) = 15
Using MatLab
cell(2, 3) = ?
20
Creating Matrices in MatLab
• In MatLab a variable can hold an entire matrix. Try the
following command
>> matvar = [2 13 5; 15 1 6]
• [ and ] are called the square brackets
• double click on the mat icon in the Workspace
Browser and examine the contents of the variable mat
Using MatLab
21
Cells in a Matrix
• Each individual cell or element is a variable
• Try the following command
>>firstvar = matvar(1,2) + matvar(2,1)
>> matvar(2,2) = 3 * matvar(2,3)
•
•
•
•
•
What is the value of firstvar now?
to refer to a particular cell of a matrix variable we use subscripts
matvar(1,2) refers to the cell at row 1, column 2
matvar(2,1) refers to the cell at row 2, column 1
matvar refers to the entire matrix
Using MatLab
22
Arrays - A Special Kind of Matrix
• A matrix with a single row is called an Array or Vector
• We will use arrays extensively this week
• There are many ways to create arrays (and matrices)
in MatLab
>> arrayvar1 = [1 4 9 16 25]
>> arrayvar2 = 1:10
>> arrayvar3 = 5:5:100
>> arrayvar4 = zeros(1,10)
>> arrayvar5 = ones(1,15)
Using MatLab
23
Loading Data from a File
• Typing in all this data can be a pain.
• Sometimes it is easier and more convenient to read
data from a file
• We will be doing this a lot this weekend
• Getting this done correctly can be a pain, but realize it
is not the essence of computer programming.
>> load cs303e/firstbytes/sampleData.dat
>> arrayvar6 = sampleList
Using MatLab
24
Referring to a Single Array Element
• MatLab treats matrices with a single row (arrays) in a special
way
• An element may be referenced without specifying the row.
• Try the following command
>> arrayvar1 = [2 3 5 7 11 13]
>> firstvar = list1(2) + list1(3)
• What is the value of firstvar now?
• Care must be taken when accessing elements of an array.
• Try the following command:
>> firstvar = arrayvar1(4) + arrayvar(10)
Using MatLab
25
Basic Operators and Functions
• MatLab basic mathematical operators
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
^ (power)
() (specify evaluation order)
• In addition to these basics MatLab has hundreds of
functions. Not a symbol, but a named function
Using MatLab
26
A Few MatLab Functions
• Format is
functionName(inputInfoList)
inputInfoList is zero or more values separated by
commas. These can be values or variables
• Try these function calls
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
abs(-101)
round(1.234)
isprime(13)
isprime(111)
factor(13)
factor(111)
list1 = factor(792)
max(3, 5)
max(firstvar, secondvar)
max(list1)
Using MatLab
27
Function Facts
• A function has inputs
– 0 or more values.
– the values can be variables
– may have different numbers of input
• A function has an output
– a single value, array, or matrix
– result can be assigned to a variable
• You can (and will) create functions to do various
tasks
– stored in a separate file, in MatLab these are called Mfiles
Using MatLab
28
Creating a Function
• Create a function that determines the area of a triangle
• to create a new M-File click the new M-File icon in MatLab
• This opens the M-File editor
• Type the first line. Need name for function, name for output,
and list of inputs
• skip 1 line
• write command(s)
• save and test in command space
Using MatLab
29
Sample Function
Using MatLab
30
Details of Function
the word
function
lets MatLab
know this is
a function
variable to
hold output
of function
name of the function
inputs to
function
function c = hyp(a,b)
% calculates length of the
% hypotenuse of a right
% triangle. (These are comments)
c = a * a + b * b;
commands.
these are carried c = sqrt(c)
out every time
optional semicolon at end
function is carried out.
of command: suppresses
This function calls another!
output of command
Using MatLab
31
Array Outputs from Functions
function result = cubedata(lengthOfSide)
result = zeros(1,3)
result(1) = 12 * lengthOfSide
result(2) = 6 * (lengthOfSide ^ 2)
result(3) = lengthOfSide ^ 3
lengthOfSide
Using MatLab
32
Another Function
• Consider a rectangular three dimensional object
Write a function whose output is an array with three
elements
1. sum of the length of the sides of the object
2. surface area of the object
3. volume of the object
Using MatLab
33
Steps to Writing a Function
• What must the function do
– what are the required inputs?
– what is the desired output?
– how do I get the desired output based on the required
input?
• Notice, the area of expertise here is geometry and
programming
– One of the joys of being a computer scientist is that
computer science is applicable to so many different
areas
Using MatLab
34
Steps to Writing a Function in MatLab
•
1.
2.
3.
4.
5.
6.
Once clear on what must be done
pick name for function
pick name for output (result)
pick names for inputs
complete commands for function
save function
test function in command window
Using MatLab
35
Programming with MatLab
Mary Eberlein and Mike Scott
Using MatLab
36
Agenda
• Programming Tool #1
– Loops, do things over and over
• Strings, another kind of variable
• Programming Tool #2
– Decision making, doing things only if certain things are
true
• starting to crack the code
– decoding a Caesar shift cipher
Using MatLab
37
Harnessing the Power
• Why use a computer?
– to manipulate data that can be stored in a numeric
format when you need to do a lot of manipulating
– the computer is fast!
• Function you wrote last time for computing
properties of a rectangular solid
– were we taxing the resources of the computer?
• the power of a computer is its speed. It can do a lot
of simple things very quickly
Using MatLab
38
Loops
• say I want a function that creates an array that holds
the squares of the first 10 positive integers in order.
– lots of different ways to do this
– one simple way
squares = [1 4 9 16 25 36 49 64 91 100]
• seems simple
• what if I want the function to create an array that
holds the squares of the first N positive integers in
order?
– N is a variable!
Using MatLab
39
First Attempt
function result = squares(N)
result = zeros(1,N)
result(1) = 1
result(2) = 4
result(3) = 9
…
• what's the problem?
Using MatLab
40
Loops are for Repetition
• A loop is a way to repeat a command a variable number
of times
– more syntax -> gain powerful tool
function result = squares(N)
result = zeros(1,N)
for num = 1:N
result(num) = num * num
end
function header
create array of
correct size
for loop
Using MatLab
41
Anatomy of a for Loop
• a for loop starts out with the word for
– this similar to the word function. It has a special meaning in
MatLab, in this case as a signal this is the start of a for loop
(reserved words or keywords)
• next comes a variable
– in the previous example this is num. This is called the loop control
variable. It determines how many times the commands of the loop
will be executed
• The next part of the loop assigns the loop control variable
an initial value, in this case 1
• the :N indicates what value the loop control variable, num,
will go up to
– so num will start at 1 and go up by 1 until it reaches N
Using MatLab
42
Inside the for loop
• after the first line of the for loop is the body of the for
loop
• this is a series of commands
– any commands you like
• these are executed in order until the end statement
is reached
– end is another special word (reserved word or keyword)
– tells MatLab this is the end of the for loop
Using MatLab
43
So What Happens?
result = zeros(1,N)
for num = 1:N
result(num) = num * num
end
num starts at 1
result(1) is set to 1 * 1
num goes up by 1 to 2
result(2) is set to 2 * 2
num goes up by 1 to 3
result(3) is set to 3 * 3
and so on and so on…
Using MatLab
44
Figuring out Square Roots
• Let's work with determining square roots
• Newton's method for approximating square roots adapted from
the Dr. Math website
The goal is to find the square root of a number. Let's call it num
1. Choose a rough approximation of the square root of num, call it
approx.
How to choose?
2. Divide num by approx and then average the quotient with
approx,
in other words we want to evaluate the
expression
((num/approx)+approx)/2
3. How close are we? In programming we would store the result of
the expression back into the variable approx.
4. How do you know if you have the right answer?
Using MatLab
45
Doing it the Hard Way
• Use variables, expressions, and assignment
commands in the command window to determine
the square root of
123456
start approx at 0.01
To speed this up we could write a function that
determines square roots using the same technique
Using MatLab
46
Write your Own Square Root Function
• don't call your function sqrt, pick some other name
• you only need a 1 x 1 matrix so you should have
result = zeros(1,1)
• Use a for loops to carry out 10 steps of the
approximation
• compare the answer from your function to the result
from the sqrt function in MatLab for the numbers
5
10
1178
108271
2137810
Using MatLab
47
Strings, Another Kind of Data
• So far we have been working with numbers
• Computers are also very useful for dealing with text
– letters and characters
• Most programming environments, including MatLab,
have a way of representing information consisting of
text
• In MatLab this is via Strings
– a collection of zero or more characters (not numbers)
– to indicate a String a pair of single quotes is used
– the characters of the String are between the single quotes
Using MatLab
48
Test this Code
string1 = 'First Bytes'
string1(1)
string1(3)
string1(7)
What is the index of the e?
string1(8) = i
nums = int8(string1)
Using MatLab
49
Encoding - Using Numbers to
Represent Something Else
• The output of the last command on the previous
page is especially interesting
– any ideas on what it means?
• Try this command
string1 = 'ABCDEFGHIJ'
nums = int8(string1)
Hmmmm
Using MatLab
50
Encoding Text
• A computer stores numbers
• Those numbers can be made to represent many,
many things for example characters
• An encoding scheme is a way to match up numbers
to the other information we want the number to
represent
• For text, letters, characters there are many encoding
schemes
• The most popular are ASCII, the America Standard
Code for Information Interchange and Unicode
Using MatLab
51
A bit of the ASCII Encoding Scheme
letter code letter code letter code letter code letter code
space
32
0
48
A
65
[
91
a
97
!
33
1
49
B
66
\
92
b
98
"
34
2
50
C
67
]
93
c
99
#
35
3
51
D
68
^
94
d
100
The computer needs a number, we are comfortable with text.
Sometimes we have to switch back and forth.
Try the following commands:
>> nums = 1:128
>> string1 = char(nums)
Using MatLab
52
Using Characters as Numbers
• Some programming languages and tools allow a
character or String with a single character to be
manipulated like numbers
– Why might this be
• Try the following commands:
>>
>>
>>
>>
shift = 13
'Z' + shift
char('Z' + shift)
char('Z' + shift - 26 + 1)
Using MatLab
53
Decision Making
• Sometimes it is necessary for your program to make a
decision
– you may or may not want the program to carry out a
command in certain cases
• Decision making is accomplished via an if statement
–
–
–
–
–
another keyword
the program tests to see if something is true
if it is carry out a series of commands
if it isn't skip those commands
one or the other
Using MatLab
54
Sample Decision Making
function result = passFailGrade(score)
result = 'Fail'
if score >= 70
result = 'Pass'
end
• after the if is a boolean condition
- this is an expression that can be evaluated to true or false
- if it is true the statements in the if are carried out
- if it is false the statements in the if are skipped
Using MatLab
55
Evaluation Tools
There are various operators to build up boolean expressions
<
<=
>
>=
==
~=
&&
||
~
less than
less than or equal to
greater than
greater than or equal to
equal to (Note difference from assignment, =)
not equal to
logical and, two conditions and both must be true
logical or, two conditions and 1 or more must be true
logical not, inverts an expression
Using MatLab
56
More Decision Making
An Alternate Version
function result = passFailGrade(score)
if score >= 70
result = 'Pass'
else
result = 'Fail'
end
If the boolean expression is true then only the commands between the if and
the else are carried out
If the boolean expression is false then only the commands between the else
and the end are carried out
Using MatLab
57
One Last Decision Making Function
function result = grade(score)
if score < 60
result = 'F'
elseif score < 70
result = 'D'
elseif score < 80
result = 'C'
elseif score < 90
result = 'B'
else
result = 'A'
Using MatLab
58
Descargar

Using MatLab First Bytes Summer Camp