Computer Programming with MatLab First Bytes Summer Camp - PowerPoint PPT Presentation

About This Presentation
Title:

Computer Programming with MatLab First Bytes Summer Camp

Description:

Computer Programming with MatLab First Bytes Summer Camp Mary Eberlein and Mike Scott Who am I? From St. Charles, Missouri Attended Stanford University 1986 - 1990 US ... – PowerPoint PPT presentation

Number of Views:112
Avg rating:3.0/5.0
Slides: 59
Provided by: csUtexas
Category:

less

Transcript and Presenter's Notes

Title: Computer Programming with MatLab First Bytes Summer Camp


1
Computer Programming with MatLabFirst Bytes
Summer Camp
  • Mary Eberlein and Mike Scott

2
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

3
(No Transcript)
4
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

5
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

6
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

7
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

8
Click this icon to maximize
WorkspaceBrowser
Command Window
CommandHistory
9
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
  • gtgt
  • type in 2 2 and press the Enter or Return key
  • What happened?

10
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.

11
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,

12
More MatLab
  • Like a calculator and algebra MatLab has
    functions
  • try this command
  • gtgt 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!!!

13
Variables
  • Try the following command
  • gtgt firstvar 12
  • what happened? Look in the Workspace Browser
    section.

14
Variables
  • There is now an entry in the Workspace Browser
    for firstvar and an icon for it
  • Try the command
  • gtgt firstvar
  • What happened?
  • Double click on the icon for firstvar in the
    Workspace Browser

15
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

16
Array Editor Window
Nameof Variable
Current Valueof Variable
Leave the Array Editor Window for firstvar open
and back inthe Command Window try the following
command gtgt firstvar 20 What happened?
17
Manipulating Variables
  • Try the following command
  • gtgt 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

18
Experiment with Assignment
  • Some of these commands purposefully have errors
  • gtgt firstvar 2
  • gtgt firstvar firstvar 2
  • gtgt firstvar firstvar 2
  • gtgt firstvar firstvar 2 2
  • gtgt firstvar firstvar 2 2
  • gtgt firstvar (firstvar 2) 2
  • gtgt firstvar 2 firstvar
  • gtgt firstVAR firstvar 2
  • gtgt firstvar firstVar 2

19
More Variable Assignment
  • gtgt firstvar 10
  • gtgt firstvar firstvar - 100
  • gtgt secondvar abs(firstvar)
  • gtgt 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

20
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 13 5
  • 15 1 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 cell(2, 3) ?

21
Creating Matrices in MatLab
  • In MatLab a variable can hold an entire matrix.
    Try the following command
  • gtgt 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

22
Cells in a Matrix
  • Each individual cell or element is a variable
  • Try the following command
  • gtgtfirstvar matvar(1,2) matvar(2,1)
  • gtgt 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

23
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
  • gtgt arrayvar1 1 4 9 16 25
  • gtgt arrayvar2 110
  • gtgt arrayvar3 55100
  • gtgt arrayvar4 zeros(1,10)
  • gtgt arrayvar5 ones(1,15)

24
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.
  • gtgt load cs303e/firstbytes/sampleData.dat
  • gtgt arrayvar6 sampleList

25
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
  • gtgt arrayvar1 2 3 5 7 11 13
  • gtgt 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
  • gtgt firstvar arrayvar1(4) arrayvar(10)

26
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

27
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
  • gtgt abs(-101)
  • gtgt round(1.234)
  • gtgt isprime(13)
  • gtgt isprime(111)
  • gtgt factor(13)
  • gtgt factor(111)
  • gtgt list1 factor(792)
  • gtgt max(3, 5)
  • gtgt max(firstvar, secondvar)
  • gtgt max(list1)

28
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 M-files

29
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

30
Sample Function
31
Details of Function
name of the function
variable tohold outputof function
inputs tofunction
the wordfunction lets MatLabknow this is a
function
  • function c hyp(a,b)
  • calculates length of the
  • hypotenuse of a right
  • triangle. (These are comments)
  • c a a b b
  • c sqrt(c)

commands.these are carried out every
time function is carried out. This function calls
another!
optional semicolon at end of command suppresses
output of command
32
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
33
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

34
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

35
Steps to Writing a Function in MatLab
  • 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

36
Programming with MatLab
  • Mary Eberlein and Mike Scott

37
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

38
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

39
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!

40
First Attempt
  • function result squares(N)
  • result zeros(1,N)
  • result(1) 1
  • result(2) 4
  • result(3) 9
  • what's the problem?

41
Loops are for Repetition
  • A loop is a way to repeat a command a variable
    number of times
  • more syntax -gt gain powerful tool

function header create array ofcorrect size
function result squares(N) result
zeros(1,N) for num 1N result(num) num
num end
for loop
42
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

43
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

44
So What Happens?
result zeros(1,N) for num 1N 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

45
Figuring out Square Roots
  • Let's work with determining square roots
  • Newton's method for approximating square roots
    adapted from the Dr. Math websiteThe goal is to
    find the square root of a number. Let's call it
    num1. 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?

46
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

47
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
    haveresult 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

48
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

49
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)

50
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

51
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

52
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 gtgt nums
1128gtgt string1 char(nums)
53
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
  • gtgt shift 13
  • gtgt 'Z' shift
  • gtgt char('Z' shift)
  • gtgt char('Z' shift - 26 1)

54
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

55
Sample Decision Making
function result passFailGrade(score) result
'Fail' if score gt 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

56
Evaluation Tools
There are various operators to build up boolean
expressions lt less than lt less than or equal
to gt greater than gt 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
57
More Decision MakingAn Alternate Version
function result passFailGrade(score) if score
gt 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
58
One Last Decision Making Function
function result grade(score) if score lt
60 result 'F' elseif score lt 70 result
'D' elseif score lt 80 result 'C' elseif score
lt 90 result 'B' else result 'A'
Write a Comment
User Comments (0)
About PowerShow.com