Project - PowerPoint PPT Presentation

1 / 241
About This Presentation
Title:

Project

Description:

Title: ACM SIGCSE 2003: Multimedia Construction Projects Author: College of Computing Last modified by: Mark Guzdial Created Date: 2/17/2003 6:04:39 PM – PowerPoint PPT presentation

Number of Views:382
Avg rating:3.0/5.0
Slides: 242
Provided by: CollegeofC162
Category:
Tags: project | writing

less

Transcript and Presenter's Notes

Title: Project


1
Project Georgia Computes!First Courses
WorkshopDay 2
  • Mark Guzdial
  • College of Computing
  • Georgia Institute of Technology
  • guzdial_at_cc.gatech.edu
  • http//www.cc.gatech.edu/mark.guzdial
  • http//www.georgiacomputes.org

2
Workshop Plan-Day 2
  • 9-1030 Introduction to Computing using Robotics
    in Python
  • 1030-1130 Tackling a homework assignment in
    Robotics
  • Follow the light
  • 1130-1230 Lunch
  • 1230-230 Introduction to Computing for
    Engienering using MATLAB
  • 230-245 Break
  • 245-430 Data Structures in Media Computation
    using Java
  • 430-5 Wrap-up discussion and evaluation of
    workshop

3
CS1 Robotics with Python
  • Microsoft Research has funded the Institute for
    Personal Robotics in Education
  • Tucker Balch, DirectingMonica Sweat, Developing
    GTs CS1
  • Joint between Bryn Mawr and Georgia Tech
  • Doug Blank (Developing Myro)
  • Deepak Kumar (Teaching their first CS1 with
    robots)
  • http//www.roboteducation.org

4
Curriculum Goals
  • Make entry into computer science more accessible
  • Revamp CS1 CS2 curricula
  • Use personal robots as a vehicle
  • Fresh approach to introducing computing
  • Influence robot design based on past experience
  • Influence software development

5
Pilot CS1 in Spring 2007
  • Offered at Bryn Mawr (Deepak Kumar) and GaTech
    (Monica Sweat)
  • Use the Parallax Scribbler robot
  • Wireless bluetooth interface designed by GaTech
    enables Scribbler interface
  • Myro software running under Dr. Python (IDE) to
    control Scribbler
  • Course will provide additional data on curriculum
    design

6
Curriculum Development Strategy
  • Step One Figure out something that students will
    want to do.
  • Step Two Teach the CS and Robotics to make that
    happen.
  • Goals
  • Relevance
  • Motivation
  • Context for Transferrable Learning

7
Example CS1 Exercises Early
  • Focus on variables, arguments, functions, giving
    commands to a computer, sequencing commands
  • Personalize your robot (use colors, pens,
    stickers, etc.). Give it a personality, and a
    specific move
  • Then experiment with difference basic robot
    movement behaviors (go forward, backward, spin,
    turn, etc.) and learn how to upload and play a
    tune. Design a series of steps for your robot to
    perform a dance while playing a tune.
  • Test the sensitivity and range of IR sensors for
    light detection, obstacle detection. The latter
    will vary depending on the reflectance of the
    object being sensed...
  • Put these results in Excel to introduce ideas of
    computational science Gathering data from
    sensors and analyzing it.

8
Example CS1 Exercises Later
  • Iteration
  • Focus on iterating, sequencing within an
    iteration, limiting iteration
  • Experiment with simple behaviors like going
    forward for a while and then backward. Repeat
    these behaviors several times. Does the robot
    track the same space or are the movements
    shifting its space? A good way to test these
    would be to insert a pen and let the robot draw
    its path each time. This will help observe and
    get used to variations in your robots motor
    behaviors.
  • Write a loop to input a sound (could be on laptop
    instead of robot) then play it back. Do this in a
    group of robots. Make a sound, allowing the group
    behavior and dynamics to create a cacophony.
  • Write programs for the robot to draw a square, a
    circle, a figure-8, a 5 point star...and other
    shapes...a spiral?

9
Example CS1 Exercises Powerful
  • Representation and Interpretation
  • Using some other data structure or sensed data as
    a command to drive other behavior
  • Create a file with commands like "left on 30 \n
    right on 30 \n beep" Write a program to read
    these commands and execute them in other words,
    define a mini robot language and write an
    interpreter for it. Gives us the opportunity to
    address string processing, a typical CS1 topic.
  • Have one robot "call out" audio commands (perhaps
    specific tones, via the speaker), and have other
    robots "hear" the commands (via microphones) and
    execute the commands.
  • Follow a line of symbols/fiducials, where the
    symbols (colors or scan codes) can be interpreted
    as music. Start the robot on the line, and as it
    encounters the markings, it plays a note. The
    spacing is the timing of the songs. Put one after
    another, and they play in a round. Have two go
    together (on two lines) and they play a harmony.
    The robot could also write the music with a pen.
    First robot writes the song, second robot plays
    it.

10
Parallax Scribbler Robot
  • Low cost (80) and features
  • 3 photosensors
  • IR sensors in front
  • IR on chasis
  • Servo controlled motors
  • 3 Programmable LEDs
  • Speaker
  • Battery operated (6 AAs)
  • Serial interface

11
Assessment Methods
  • Within term
  • Initial, midterm, final surveys.
  • Focus group or individual student interviews.
  • Across term
  • Tracking do they stay in CS?How well do they
    do?

12
Installing Myro on Windows
  1. Download the latest Myro from http//wiki.robotedu
    cation.org/Windows_Setup
  2. Save it, open it, and expand it.
  3. Double-click on install.bat

13
Setting up Bluetooth
14
Testing Myro
15
Testing the Robot
In other words initialize(com5)
16
Controlling the robots motors
  • Most Myro robot movement functions control the
    speed (specifically, amount of power) of the
    motor.
  • motors(1.0,0.5) Gives full power to motor
    Left, half power to motor Right
  • forward(1.0) Both motors, full speed ahead
  • backward(0.5) Backwards, half speed
  • turnLeft (0.1) Turn left, slowly
  • turnRight(0.25) Turn right, slightly more
    quickly
  • stop() STOP EVERYTHING
  • same as motors(0,0)

17
Defining a robot function Yoyo
  • def yoyo()
  • forward(1)
  • wait(1) Wait one second
  • backward(1)
  • wait(1)
  • stop()

Can just type this in, and then execute it
as yoyo() Or can enter it into a module
(filename)
18
Parameterizing our YoYo
  • def yoyo1(speed)
  • forward(speed)
  • wait(1) Wait one second
  • backward(speed)
  • wait(1)
  • stop()

19
Further parameterizing
  • def yoyo2(speed, wait)
  • forward(speed)
  • wait(wait) Wait a bit
  • backward(speed)
  • wait(wait)
  • stop()

20
Can do something forever
  • from myro import
  • initialize(com5)
  • def yoyo2(speed, wait)
  • forward(speed)
  • wait(wait) Wait one second
  • backward(speed)
  • wait(wait)
  • stop()
  • def wiggle(speed,waitTime)
  • rotate(speed)
  • wait(waitTime)
  • rotate(-speed)
  • wait(waitTime)
  • stop()
  • def dance()
  • while True
  • yoyo2(1.0,1)
  • wiggle(1.0,0.2)
  • yoyo2(0.5,0.5)
  • wiggle(0.5,0.5)

Use Control-C to stop this.
21
Using the robot as an object
Robot can be controlled using global
functions,or as methods to robot objects.
22
Review
  • from myro import
  • robot Scribbler(com4)
  • robot.turnRight(0.25) wait(0.25) robot.stop()
  • robot.forward(0.25) wait(0.25) robot.stop()
  • def function()
  • while True

23
Reading the Light Sensors
  • robot.getLight(0)
  • robot.getLight(1)
  • robot.getLight(2)
  • gtgtgt robot.getLight()
  • 657, 1453, 1025

Light sensors
24
Which one is which?
  • Exercise Playing blind mans bluff
  • 0,1,2 left, right, center?
  • Do the values go up with darkness or with light?

25
Modeling Animals
  • How do animals sense light?
  • Why do moths move to the light?
  • How do they know which way to turn to get there?
  • Does it matter if you see vs. smell?
  • Lets model light-seeking behavior

26
Choosing action depending on senses
  • New statement if
  • Allows us to test conditions (logical
    expressions) and choose actions based on those
    conditions.
  • if (some logical test goes here)
  • The actions go on the line below, indented.
  • if robot.getLight(0) gt 800
  • robot.turnLeft(0.25)

27
Blocks
  • Just like the lines after def and while, all the
    lines indented the same after if are part of the
    same block
  • A block is defined in Python by indentation.
  • Lines at the same level of indentation are in the
    same block.
  • A block is used to define the body of a function
    and the loop.
  • A block is used to define the actions of a
    successful if test.

28
Wheres the light?
  • We can compare against a value, but what we
    really care about is the relative light values.
  • if robot.getLight(0) gt robot.getLight(2)
  • print "LEFT!"

29
Signaling a Turn
  • def signalingTurn()
  • left 0
  • right 2
  • while True
  • if robot.getLight(left) lt
    robot.getLight(right)
  • print Left!"
  • if robot.getLight(right) lt
    robot.getLight(left)
  • print "Right!"
  • signalingTurn()

30
Audibly signaling a turn
  • def signalingTurn()
  • left 0
  • right 2
  • while True
  • if robot.getLight(left) lt
    robot.getLight(right)
  • robot.beep(0.25,400)
  • if robot.getLight(right) lt
    robot.getLight(left)
  • robot.beep(0.25,800)
  • signalingTurn()

31
Making Music
  • beep(1,400) Plays at frequency 400 Hz
    for 1 second
  • computer.beep(0.5,440)
  • Has the computer beep at A-above-middle C
  • (440 Hz) for ½ second

Can they play a duet?Try it!
32
Myro Song Format
  • Myro has a more music-like format that it
    supports
  • s makeSong(c 1 d .5 d4 1/2)
  • C in the fifth octave for a whole note
  • D in the fifth octave for a 1/2 note
  • D-sharp in fourth octave for a 1/2 note
  • robot.playSong(s,0.75) Play this for ¾ second

33
Exercises
  • Option 1 Follow the Light
  • Write a function that will turn the robot toward
    the light, much as an insect might follow the
    light.
  • Can you turn based on the amount of light?
  • Option 2 Make the Robot Dance
  • Write a program to play music and dance your
    Scribbler
  • Use beep() and playSong to make music
  • Use movements like yoyo and wiggle

34
CS1 for Engineering in MATLAB
  • Syllabus
  • Sample lessons on getting started

35
Syllabus
  • Getting started with MATLAB
  • Introduction to Vectors, the main MATLAB data
    type
  • Conditionals, iteration, and functions
  • Cell arrays (mini-databases)
  • Structures
  • Problem solving
  • General arrays
  • Graphing (MATLAB does professional quality
    graphics)
  • Bodies of Rotation and Matrices
  • File I/O
  • Multimedia Image and sound manipulation
  • Serious CS Numerical methods, Big O, Sorting,
    Queues, and Graphs

36
Objectives the MATLAB User Interface
  • How to use the Command window to explore single
    commands interactively and how to recall earlier
    commands to be repeated or changed
  • Where to examine the variables and files
    created in MATLAB
  • How to view and edit data tables created in
    MATLAB
  • How MATLAB presents graphical data in separate
    windows
  • How to create scripts to solve simple
    arithmetic problems

37
The Default Window
File menu
Close icon
Current directory
Current directory
Command window
Workspace window
Command history
38
Array Editor
New variable icon
39
If you dont have MATLAB, Octave!
40
2.4 Scripts
  • Create a script derived from the Pythagorean
    theorem to compute the hypotenuse of a right
    triangle
  • H2 A2 B2
  • where A and B are the sides adjacent to the right
    angle, and H is the hypotenuse opposite.
  • clear
  • clc
  • A 3 the first side of a triangle
  • B 4 the second side of a triangle
  • hypSq A2 B2 the square of the
  • hypotenuse
  • H sqrt(hypSq) the answer

41
2.5 Engineering ExampleSpacecraft Launch
  • clear
  • clc
  • cmPerInch 2.54 general knowledge
  • inchesPerFt 12 general knowledge
  • metersPerCm 1/100 general knowledge
  • MetersPerFt metersPerCm cmPerInch
    inchesPerFt
  • startFt 25000 ft - given
  • startM startFt MetersPerFt
  • g 9.81 m/sec2
  • top 100 km - given
  • s (top1000) - startM m
  • initial_v (2gs)0.5 the final answer

42
3.1 Concept Using Built-in Functions
  • In this chapter we will see the use of some of
    the functions built into MATLAB.
  • At the end of each chapter that uses built-in
    functions, you will find a summary table listing
    the function specifications.
  • For help on a specific function, you can type the
    following
  • gtgt help ltfunction namegt
  • For example
  • gtgt help sqrt
  • SQRT Square root.
  • SQRT(X) is the square root of the elements of
    X. Complex results are produced if X is not
    positive.

43
3.2 Concept Data Collections
  • This section considers two very common ways to
    group data in arrays and in vectors.
  • Data Abstraction allows us to refer to groups of
    data collectively
  • all the temperature readings for May or
  • all the purchases from Wal-Mart.
  • We can not only move these items around as a
    group, but also perform mathematical or logical
    operations on these groups, e.g.
  • compute the average, maximum, or minimum
    temperatures for a month
  • A Homogeneous Collection is constrained to accept
    only items of the same data type in this case,
    they will all be numbers

44
3.3 MATLAB Vectors
  • Individual items in a vector are usually referred
    to as its elements. Vector elements have two
    separate and distinct attributes that make them
    unique in a specific vector
  • their numerical value and
  • their position in that vector.
  • For example, the individual number 66 is the
    third element in this vector. Its value is 66 and
    its index is 3. There may be other items in the
    vector with the value of 66, but no other item
    will be located in this vector at position 3.

45
Vector Manipulation
  • We consider the following basic operations on
    vectors
  • Creating a Vector
  • Determining the size of a Vector
  • Extracting data from a vector by indexing
  • Shortening a Vector
  • Mathematical and logical operations on Vectors

46
Creating a Vector Constant Values
  • Entering the values directly, e.g.
  • A 2, 5, 7, 1, 3
  • Entering the values as a range of numbers e.g.,
  • B 1320
  • Using the linspace(...) function e.g.
  • C linspace (0, 20, 11)
  • Using the functions zeros(1,n), ones(1,n),
    rand(1,n) and randn(1,n) to create vectors
    filled with 0, 1, or random values between 0 and
    1

47
Size of Vectors and Arrays
  • MATLAB provides two functions to determine the
    size of arrays in general (a vector is an array
    with one row)
  • the function size(A) when applied to the array A
    returns vector containing two quantities the
    number of rows and the number of columns
  • The function length(A) returns the maximum value
    in the size of an array for a vector, this is
    its length.

48
Indexing a Vector
  • The process of extracting values from a vector,
    or inserting values into a vector
  • Syntax
  • v(index) returns the element(s) at the
    location(s) specified by the vector index.
  • v(index) value replaces the elements at the
    location(s) specified by the vector index.
  • The indexing vector may contain either numerical
    or logical values

49
Numerical Indexing
  • The indexing vector may be of any length
  • It should contain integer (non-fractional)
    numbers
  • The values in the indexing vector are constrained
    by the following rules
  • For reading elements, all index values must be
  • 1 lt element lt length(vector)
  • For replacing elements, all index values must be
  • 1 lt element

50
Replacement Rules
  • Either
  • All dimensions of the blocks on either side of
    the replacement instruction must be equal, or
  • There must be a single element on the RHS of the
    replacement
  • If you replace beyond the end of the existing
    vector, the vector length is automatically
    increased.
  • Any element not specifically replaced remains
    unchanged.
  • Elements beyond the existing length not replaced
    are set to 0.

51
Logical Indexing
  • The indexing vector length must be less than or
    equal to the original vector length
  • It must contain logical values (true or false)
  • Access to the vector elements is by their
    relative position in the logical vector
  • When reading elements, only the elements
    corresponding to true index values are returned
  • When replacing elements, the elements
    corresponding to true index values are replaced
  • Beware logical vectors in Matlab echo in the
    Command window as 1 or 0, but they are not the
    same thing.

52
Shortening an Array
  • Never actually necessary. It is advisable to
    extract what you want by indexing rather than
    removing what you dont want.
  • Can lead to logic problems when changing the
    length of a vector
  • Accomplished by assigning the empty vector ()
    to elements of a vector, or to complete rows or
    columns of an array.

53
Operating on Vectors
  • Three techniques extend directly from operations
    on scalar values
  • Arithmetic operations
  • Logical operations
  • Applying library functions
  • Two techniques are unique to arrays in general,
    and to vectors in particular
  • Concatenation
  • Slicing (generalized indexing)

54
Arithmetic operations
  • In the Command window, enter the following
  • gtgt A 2 5 7 1 3
  • gtgt A 5
  • ans
  • 7 10 12 6 8
  • gtgt A . 2
  • ans
  • 4 10 14 2 6
  • gtgt B -113
  • B
  • -1 0 1 2 3

55
Arithmetic operations (continued)
  • gtgt A . B element-by-element multiplication
  • ans
  • -2 0 7 2 9
  • gtgt A B matrix multiplication!!
  • ??? Error using gt mtimes
  • Inner matrix dimensions must agree.
  • gtgt C 1 2 3
  • C
  • 1 2 3
  • gtgt A . C A and C must have the same length
  • ??? Error using gt times
  • Matrix dimensions must agree.

56
Logical operations
  • gtgt A 2 5 7 1 3
  • gtgt B 0 6 5 3 2
  • gtgt A gt 5
  • ans
  • 0 1 1 0 0
  • gtgt A gt B
  • ans
  • 1 0 1 0 1
  • gtgt C 1 2 3
  • gtgt A gt C
  • ??? Error using gt gt
  • Matrix dimensions must agree.

57
Logical operations (continued)
  • gtgt A true true false false
  • gtgt B true false true false
  • gtgt A B
  • ans
  • 1 0 0 0
  • gtgt A B
  • ans
  • 1 1 1 0
  • gtgt C 1 0 0 NOT a logical vector
  • gtgt A(C) yes, you can index logical vectors, but
    ...
  • ??? Subscript indices must either be real
    positive integers or logicals.

58
A Footnote the find function
  • Continuing the code above
  • gtgt C find(B)
  • ans
  • 1 3
  • The find(...) function consumes a logical vector
    and returns the numerical indices of the elements
    of that vector that are true.

59
Applying library functions
  • All MATLAB functions accept vectors of numbers
    rather than single values and return a vector of
    the same length.
  • Special Functions
  • sum(v) and mean(v) consume a vector and return
    a number
  • min(v) and max(v) return two quantities the
    minimum or
  • maximum value in a vector, plus the position in
    that vector
  • where that value occurred.
  • round(v), ceil(v), floor(v), and fix(v) remove
    the fractional part of the numbers in a vector by
    conventional rounding, rounding up, rounding
    down, and rounding toward zero, respectively.

60
Concatenation
  • MATLAB lets you construct a new vector by
    concatenating other vectors
  • A B C D ... X Y Z
  • where the individual items in the brackets may be
    any vector defined as a constant or variable, and
    the length of A will be the sum of the lengths of
    the individual vectors.
  • A 1 2 3 42
  • is a special case where all the component
    elements are scalar quantities.

61
Slicing (generalized indexing)
  • A(4) actually creates an anonymous 1 1 index
    vector, 4, and then using it to extract the
    specified element from the array A.
  • In general,
  • B(ltrangeBgt) A(ltrangeAgt)
  • where ltrangeAgt and ltrangeBgt are both index
    vectors, A is an existing array, and B can be an
    existing array, a new array, or absent altogether
    (giving B the name ans). The values in B at the
    indices in ltrangeBgt are assigned the values of A
    from ltrangeAgt .

62
Rules for Slicing
  • Either the dimensions of ltrangeBgt must be equal
    to the dimensions of ltrangeAgt or ltrangeAgt must be
    of size 1
  • If B did not exist before this statement was
    implemented, it is zero filled where assignments
    were not explicitly made
  • If B did exist before this statement, the
    values not directly assigned in ltrangeBgt remain
    unchanged

63
Representing Mathematical Vectors
  • An unfortunate clash of names
  • Vectors in mathematics can be represented by
    Matlab vectors
  • The first, second and third values being the x, y
    and z components
  • Matlab vector addition and subtraction work as
    expected.
  • Matlab magnitude and scaling works as expected.
  • Dot product is just the sum of A . B
  • Cross product has a Matlab function

64
Engineering ExampleForces and Moments
  • So given a pair of forces A and B acting at a
    point P, find
  • The resultant force, and
  • The moment of that resultant about the origin

65
Vector Solution
  • clear
  • clc
  • PA 0 1 1
  • PB 1 1 0
  • P 2 1 1
  • M 4 0 1
  • find the resultant of PA and PB
  • PC PA PB
  • find the unit vector in the direction of PC
  • mag sqrt(sum(PC.2))
  • unit_vector PC/mag
  • find the moment of the force PC about M
  • this is the cross product of MP and PC
  • MP P - M
  • moment cross( MP, PC )

66
MATLAB Arrays
67
A Transposed Array
68
Array Manipulation
  • We consider the following basic operations on
    vectors
  • Creating an array
  • Extracting data from an array by indexing
  • Shortening an array
  • Mathematical and logical operations on arrays

69
Creating an Array Constant Values
  • Entering the values directly, e.g.
  • A 2, 5, 7 1, 3, 42 the semicolon
    identifies the next row, as would a new line in
    the command
  • Using the functions zeros( rows, cols),
    ones(rows, cols), rand(rows, cols) and
    randn(rows, cols) to create vectors filled with
    0, 1, or random values between 0 and 1

70
Indexing an Array
  • The process of extracting values from an array,
    or inserting values into an array
  • Syntax
  • A(row, col) returns the element(s) at the
    location(s) specified by the array row and column
    indices.
  • A(row, col) value replaces the elements at the
    location(s) specified by the array row and column
    indices.
  • The indexing row and column vectors may contain
    either numerical or logical values

71
Numerical Indexing
  • The indexing vectors may be of any length
  • It should contain integer (non-fractional)
    numbers
  • The values in the indexing vectors are
    constrained by the following rules
  • For reading elements, all index values must be
  • 1 lt element lt length(array dimension)
  • For replacing elements, all index values must be
  • 1 lt element

72
Replacement Rules
  • Either
  • All dimensions of the blocks on either side of
    the replacement instruction must be equal, or
  • There must be a single element on the RHS of the
    replacement
  • If you replace beyond the end of any dimension of
    the existing array, the size in that dimension is
    automatically increased.
  • Any element not specifically replaced remains
    unchanged.
  • Elements beyond the existing dimension length not
    replaced are set to 0.

73
Logical Indexing
  • The indexing vector length must be less than or
    equal to the original array dimension
  • It must contain logical values (true or false)
  • Access to the array elements is by their relative
    position in the logical vectors
  • When reading elements, only the elements
    corresponding to true index values are returned
  • When replacing elements, the elements
    corresponding to true index values are replaced

74
Operating on Arrays
  • Four techniques extend directly from operations
    on vectors
  • Arithmetic operations
  • Logical operations
  • Applying library functions
  • Slicing (generalized indexing)
  • The following deserves an additional word because
    of the nature of arrays
  • Concatenation

75
Array Concatenation
  • Array concatenation can be accomplished
    horizontally or vertically
  • R A B C succeeds as long as A, B and C have
    the same number of rows the columns in R will be
    the sum of the columns in A, B and C.
  • R A B C succeeds as long as A, B and C have
    the same number of columns the rows in R will be
    the sum of the rows in A, B and C.

76
Reshaping Arrays
  • Arrays are actually stored in column order in
    Matlab. So internally, a 2 3 array is stored
    as a column vector A(1,1)
  • A(2,1)
  • A(1,2)
  • A(2,2)
  • A(1,3)
  • A(2,3)
  • Any n m array can be reshaped into any p q
    array as long as nm pq using the reshape
    function.

77
3.6 Engineering ExampleComputing Soil Volume
  • Consider the example where you are given the
    depth of soil from a survey in the form of a
    rectangular array of soil depth.
  • You are also given the footprint of the
    foundations of a building to be built on that
    site and the depth of the foundation.
  • Compute the volume of soil to be removed.

78
Survey Data
79
Building Footprint
80
Solution
  • clear
  • clc
  • soil depth data for each square produced
  • by the survey
  • dpth 8 8 9 8 8 8 8 8 7 8 7 7 7 7 8 8 8 7
  • 8 8 8 8 8 8 8 7 7 7 7 7 8 7 8 8 8 7
  • . . .
  • 9 8 8 7 7 8 7 7 7 7 8 8 9 9 9 8 7 8
  • estimated proportion of each square that should
  • be excavated
  • area 1 1 1 1 1 1 1 1 1 1 .3 0 0 0 0 0 0 0
  • . . .
  • 0 0 0 0 0 0 .4 .8 .9 1 1 1 1 1 1 1 1 .6
  • square_volume dpth . area
  • total_soil sum(sum(square_volume))

81
4.1 Concept Code Blocks
  • A code block is a collection of zero or more
    MATLAB instructions identified for one of two
    reasons
  • you wish to execute them only under certain
    circumstances, or
  • You wish to repeat them a certain number of times
  • Some languages identify code blocks by enclosing
    them in braces (. . .) others identify them by
    the level of indentation of the text.
  • MATLAB uses the occurrence of key command words
    in the text to define the extent of code blocks
  • if, switch, while, for, case, otherwise, else,
    elseif, end
  • Code blocks are identified with blue coloring by
    the MATLAB text editor. They are not part of the
    code block, but they serve both
  • as instructions on what to do with the code
    block, and
  • as delimiters that define the extent of the code
    block.

82
4.2 Conditional Execution in General
  • Basic conditional execution requires two things
  • A logical expression, and
  • A code block
  • If the expression is true, the code block is
    executed.
  • Otherwise, execution is resumed at the
    instruction following the code block

83
Compound conditionals
  • By introducing elseif and else, we allow for the
    possibility of either conditional or
    unconditional execution when a test returns false
    as illustrated.

84
4.3 if Statements
  • The general template for if statements is
  • if ltlogical expression 1gt
  • ltcode block 1gt
  • elseif ltlogical expression 2gt
  • ltcode block 2gt
  • .
  • .
  • .
  • elseif ltlogical expression ngt
  • ltcode block ngt
  • else
  • ltdefault code blockgt
  • end

85
General Observations
  • A logical expression is any statement that
    returns a logical result.
  • If that result is a logical vector, v, the if
    statement behaves as
  • if all(v)
  • While indentation has no effect on the logical
    flow, it helps to clarify the logical flow. The
    MATLAB editor automatically creates suitable
    indentation as you type.

86
4.4 switch Statements
  • The template for a switch statement is
  • switch ltparametergt
  • case ltcase specification 1gt
  • ltcode block 1gt
  • case ltcase specification 2gt
  • ltcode block 2gt
  • .
  • .
  • case ltcase specification ngt
  • ltcode block ngt
  • otherwise
  • ltdefault code blockgt
  • end

87
General Observations
  • The switch statement is looking for the parameter
    to have an exact match to one of the cases.
  • One case specification may have multiple values
    enclosed in braces( ).
  • The default case catches any values of the
    parameter other than the specified cases.
  • The default case should trap bad parameter values.

88
4.5 Iteration in General
  • Iteration allows controlled repetition of a code
    block. Control statements at the beginning of the
    code block specify the manner and extent of the
    repetition
  • The for loop is designed to repeat its code block
    a fixed number of times and largely automates the
    process of managing the iteration.
  • The while loop is more flexible in character. Its
    code block can be repeated a variable number of
    times. It is much more of a do-it-yourself
    iteration kit.

89
4.6 for Loops
  • The template for a for loop is
  • for ltvariablegt ltvectorgt
  • ltcode blockgt
  • end
  • The for loop automatically sets the value of the
    variable to each element of the vector in turn
    and executes the code block with that value.

90
4.7 while Loops
  • The code block will be repeated
  • as long as the logical expression
  • returns true.
  • The while loop template is
  • ltinitializationgt
  • while ltlogical expressiongt
  • ltcode blockgt
  • must make some changes
  • to enable the loop to terminate
  • end

91
4.8 Engineering ExampleComputing Liquid Levels
  • Give a tank as shown, how do you calculate the
    volume of liquid? The answer of course is it
    depends on h.
  • If h lt r, do one calculation
  • otherwise if h lt (H-r) do a second
  • Otherwise if h lt H, do a third
  • Otherwise there is an error!

92
The Solution
  • if h lt r
  • v (1/3)pih.2.(3r-h)
  • elseif h lt H-r
  • v (2/3)pir3 pir2(h-r)
  • elseif h lt H
  • v (4/3)pir3 pir2(H-2r) ...
  • - (1/3)pi(H-h)2(3r-Hh)
  • else
  • disp(liquid level too high)
  • continue
  • end
  • fprintf( ...
  • 'rad 0.2f ht 0.2f level 0.2f vol 0.2f\n',
    ...
  • r, H, h, v)

93
5.1 Concept Abstraction
  • Procedural abstraction permits a code block that
    solves a particular sub-problem to be packaged
    and applied to different data inputs.
  • analogous to the concept of data abstraction
    where individual data items are gathered to form
    a collection.
  • We have already used a number of built-in
    procedural abstractions in the form of functions.
  • They allow us to apply a code block about which
    we know nothing to data that we provide.

94
5.1 Concept Encapsulation
  • Encapsulation is the concept of putting a wrapper
    around a collection that you wish to protect from
    outside influence.
  • Functions encapsulate the code they contain in
    two ways
  • the variables declared within the function are
    not visible from elsewhere, and
  • the functions ability to change the values of
    variables (otherwise known as causing side
    effects) is restricted to its own code body.

95
5.2 Black Box View of a Function
  • ltparam 1...ngt are the formal parameters the
    names given to the incoming data inside the
    function.
  • ltitem 1...ngt are the actual parameters provided
    to the function by its caller.
  • They may have names different from the formal
    parameter names
  • They are correlated to the formal parameter names
    by their position

96
5.3 MATLAB Implementation
  • The template for defining a function is
  • function ltreturn infogt ltfunction namegt
    (ltparametersgt)
  • ltdocumentationgt
  • ltcode bodygt must return the results
  • The function code must be stored in a file whose
    name is the name of the function.
  • Functions return data to the caller by assigning
    values to the return variable(s)
  • MATLAB throws an error if a function does not
    make assignments to all the return variables.

97
5.4 Engineering ExampleMeasuring a Solid Object
  • We need to compute the volume and wetted area of
    this object.
  • This requires one function that computes the
    volume and wetted area of a cylinder
  • We have a range of disk heights for which we
    require this information.

98
Solution
  • The function stored in cylinder.m
  • function area, volume cylinder(height,
    radius)
  • function to compute the area and volume of a
    cylinder
  • usage area, volume cylinder(height,
    radius)
  • base pi . radius.2
  • volume base . height
  • area 2 pi radius . height 2 base
  • The test script
  • clear
  • clc
  • h 15 set a range of disk thicknesses
  • R 25
  • r 3
  • Area Vol cylinder(h, R) dimensions of large
    disk
  • area vol cylinder(h, r) dimensions of the
    hole
  • compute remaining volume
  • Vol Vol - 8vol
  • Area Area 8(area - 22pir.2)

99
Background
  • Two relationships between characters and numbers
  • Individual characters have an internal numerical
    representation The shapes we see in windows are
    created by a character generator.
  • Strings of characters represent numerical values
  • Numerical values are stored in MATLAB in a
    special, internal representation for efficient
    numerical computation.
  • Whenever we need to see the value of a number,
    the internal representation is converted into a
    character string representing its value in a form
    we can read.
  • Similarly, to enter numerical values, we create a
    character string and have it converted to the
    internal representation

100
Concept Mapping
  • Mapping defines a relationship between two
    entities. e.g. the idea that the function f(x)
    x2 defines the mapping between the value of x and
    the value
  • of f(x).
  • We will apply that concept to the process of
    translating a character (like A) from its
    graphical form to a numerical internal code.
    Character mapping allows each individual graphic
    character to be uniquely represented by a
    numerical value.

101
Concept Casting
  • Casting is the process of changing the way a
    language views a piece of data without actually
    changing the data value.
  • Under normal circumstances, a language like
    MATLAB automatically presents a set of data in
    the right form.
  • However, there are times when we wish to force
    the language to treat a data item in a specific
    way we might want to view the underlying
    numerical representation as a number rather that
    as a character, in which case we have to cast the
    variable containing the character to a numerical
    data type.
  • MATLAB implements casting as a function with the
    name of the data type expected. In essence, these
    functions implement the mapping from one
    character representation to another.

102
MATLAB Implementation of Casting
  • gtgt uint8('A') uint8 is an integer data type
  • with values 0 - 255
  • ans 65
  • gtgt char(100) char is the character class
  • ans d
  • gtgt char(97 98 99 100 101)
  • ans abcde
  • gtgt double('fred')
  • ans 102 114 101 100
  • gtgt fred 'Fred'
  • fred Fred
  • gtgt next fred 1
  • next 71 115 102 101
  • gtgt a uint8(fred)
  • a 70 114 101 100
  • gtgt name char(a 1)
  • name Gsfe

103
String Operations
  • Since strings are internally represented as
    vectors of numbers, all the normal vector
    operations apply
  • Arithmetic and logical operations
  • Concatenation
  • Shortening
  • Indexing
  • Slicing

104
Conversion from Numbers to Strings
  • Use the following built-in MATLAB functions for a
    simple conversion of a single number, x, to its
    string representation
  • int2str(x) if you want it displayed as an integer
    value
  • num2str(x, n) to see the decimal parts the
    parameter n represents the number of decimal
    places requiredif not specified, its default
    value is 3
  • sprintf() provides finer-grained format control
  • Its first parameter is a format control string
    that defines how the resulting string should be
    formatted.
  • A variable number of value parameters follow the
    format string, providing data items as necessary
    to satisfy the formatting.

105
Format Control in sprintf()
  • Characters in the format string are copied to the
    result string.
  • Special behavior is introduced by two special
    characters
  • '' introduces a conversion specification
  • d (integer),
  • f (real),
  • g (general),
  • c (character) and
  • s(string).
  • Each conversion requires a value parameter in the
    sprintf() call.
  • A number may be placed immediately after the
    character to specify the minimum number of
    characters in the conversion. The f and g
    conversions can include '.n' to indicate the
    number of decimal places required.
  • '\' introduces escape characters for format
    control. The most common
  • \n (new line) and
  • \t (tab).

106
Conversion from Strings to Numbersinput()
  • When possible, allow input(...) to do the
    conversion.
  • The function input(str) presents the string
    parameter to the user in the Command window and
    waits for the user to type some characters and
    the Enter key, all of which are echoed in the
    Command window. Then it converts the input string
    according to the following rules. If the string
    begins with
  • a numerical character, MATLAB converts the string
    to a number
  • An alpabetic character, MATLAB constructs a
    variable name and looks for its definition
  • an open bracket, '', an array is constructed
  • the single quote character, MATLAB creates a
    string
  • If a format error occurs, MATLAB repeats the
    prompt.
  • This behavior can be modified if 's' is provided
    as the second parameter to input(), in which
    case the complete input character sequence is
    saved as a string regardless of content.

107
Conversion from Strings to Numbers sscanf
  • In its simplest form, CV sscanf(str, fmt) scans
    the string str and converts each data item
    according to the conversion specifications in the
    format string fmt.
  • Each item discovered in str produces a new row on
    the result array, CV, a column vector.
  • If you convert strings this way, each character
    in the string becomes a separate numerical result
    in the output vector.
  • MATLAB allows you to substitute thecharacter ''
    for the conversion size parameter to suppress any
    strings in the input string. For example
  • str 'are 4.700 1.321 4.800000'
  • B sscanf( str, 's f f f')
  • B
  • 4.7000
  • 1.3210
  • 4.8000

108
Miscellaneous Character String Operations
  • disp() shows the contents of a variable in the
    Command Window
  • fprintf() formats data for the Command Window
    exactly as sprintf does to produce a string.

109
String Comparison
  • Strings may be compared as vectors however, they
    must then obey vector comparison rules
  • strcmp() and strcmpi() compare strings of any
    length.
  • gtgt 'abcd' 'abcd'
  • ans 1 1 1 1
  • gtgt 'abcd' 'abcde'
  • ??? Error using gt eq
  • Array dimensions must match for binary array op.
  • gtgt strcmp('abcd', 'abcde')
  • ans 0
  • gtgt strcmp('abcd', 'abcd')
  • ans 1
  • gtgt 'abc' 'a'
  • ans 1 0 0
  • gtgt strcmpi('ABcd', 'abcd')
  • ans 1

110
6.5 Arrays of Strings
  • Character string arrays can be constructed by
    either of the following
  • As a vertical vector of strings, all of which
    must be the same length
  • By using a special version of the char() cast
    function that accepts a variable number of
    strings with different lengths, pads them with
    blanks to make all rows the same length, and
    stores them in an array of characters

111
Engineering ExampleEncryption
  • Encryption is the process of somehow changing a
    message in the form of a string of characters so
    that it
  • can be understood at its destination, but
  • is unintelligible to a third party who does not
    have access to the original encryption scheme.
  • Early encryption schemes involved shifting
    characters in the alphabet either by a constant
    amount or according to a one-time message pad.
  • However, these schemes are relatively easily
    cracked by examining letter frequencies.

112
Our Approach
  • We will use a scheme that makes use of the MATLAB
    random number generator to create a random
    character shift unique to each occurrence of
    characters in a message, so that letter frequency
    cannot be used to determine the encryption
    technique.
  • At the destination, as long as the random number
    generator is seeded with an agreed value, the
    message can be reconstructed by shifting back the
    message characters.
  • A few minor modifications wrap the characters on
    the alphabet to remain within the set of
    printable letters.

113
The Solution - encryption
  • encryption section
  • seed the random generator to a known state
  • rand('state', 123456)
  • loch 33
  • hich 126
  • range hich1-loch
  • rn floor( range rand(1, length(txt) ) )
  • change (txtgtloch) (txtlthich)
  • enc txt
  • enc(change) enc(change) rn(change)
  • enc(enc gt hich) enc(enc gt hich) - range
  • disp('encrypted text')
  • encrypt char(enc)

114
The Solution - decryption
  • good decryption
  • seed the random generator to the same state
  • rand('state', 123456)
  • rn floor( range rand(1, length(txt) ) )
  • change (encryptgtloch) (encrypt lt hich)
  • dec encrypt
  • dec(change) dec(change) - rn(change) range
  • dec(dec gt hich) dec(dec gt hich) - range
  • disp('good decrypt')
  • decrypt char(dec)

115
String Functions
  • num2str(a,n) Converts a number to its numerical
    representation with n decimal places
  • disp(...) Displays matrix or text
  • fprintf(...) Prints formatted information
  • input(...) Prompts the user to enter a value
  • sscanf(...) Formats input conversion
  • sprintf(...) Formats a string result
  • strcmp(s1, s2) Compares two strings returns true
    if equal
  • strcmpi(s1, s2) Compares two strings without
    regard to case returns true if equal

116
11.1 Plotting in General
  • The fundamental container for plotting is a
    MATLAB figure
  • Simple plot of x versus y plot(x, y)
  • Plot enhancements
  • axis, colormap, grid on, hold on, legend,
    shading, text, title, view, xlabel, ylabel,
    zlabel
  • Use subplot(r, c, n) for multiple plots on one
    figure

1-116
117
Plot Enhancements
1. clf 2. x -2pi.052pi 3.
subplot(2,3,1) 4. plot(x, sin(x)) 5. title('1 -
sin(x)') 6. subplot(2,3,2) 7. plot(x,
cos(x)) 8. title('2 - cos(x)') 9.
subplot(2,3,3) 10. plot(x, tan(x)) 11. title('3 -
tan(x)') 12. subplot(2,3,4) 13. plot(x,
x.2) 14. title('4 - x2') 15.
subplot(2,3,5) 16. plot(x, sqrt(x)) 17. title('5
- sqrt(x)') 18. subplot(2,3,6) 19. plot(x,
exp(x)) 20. title('4 - ex')
1-117
118
11.2 2-D Plotting
  • Basic function for 2-D plots plot(x, y, str)
  • x and y are vectors of the same length
  • str specifies optional line color style control
  • Plot options
  • subplot, axis, hold on, title
  • Parametric plotting
  • Allows the variables on each axis to be dependent
    on a separate, independent variable

1-118
119
Multiple 2-D Plots
1-119
120
Special 2-D Effects
Code for the first three plots 1. clear 2.
clc 3. close all 4. x linspace(0, 2pi) 5.
subplot(2, 3, 1) 6. plot(x, sin(x)) 7. axis(0
2pi -0.5 0.5) 8. title('Changing Data Range on
an Axis') 9. subplot(2, 3, 2) 10. plot(x,
sin(x)) 11. hold on 12. plot(x, cos(x)) 13. axis
tight 14. title('Multiple Plots with hold
on') 15. subplot(2, 3, 3) 16. plot(x, sin(x),
'ó') 17. hold on 18. plot(x, cos(x), 'r') 19.
axis tight 20. title('Multiple Plots with hold
on')
1-120
121
Transforming a Circle to an Airfoil
1-121
122
11.3 3-D Plotting
  • 2-D plots in MATLAB are actually 3-D plots
    (select the Rotate 3D icon on the tool bar)
  • Linear 3-D Plots
  • Extend 2-D plots by adding a set of z values
  • Use plot3(x, y, z, str)
  • Linear Parametric 3-D Plots
  • Allow variables on each axis to be dependent on a
    separate, independent variable
  • Other plot capabilities
  • bar3(x, y), barh3(x, y), pie3(y)

1-122
123
3-D View of a 2-D Plot
1-123
124
3-D Line plots
1-124
125
Parametric Line Plots
1-125
126
11.4 Surface Plots
  • Production of images based on mapping a 2-D
    surface ? create a plaid
  • Basic capabilities
  • meshgrid(x, y) compute mappings for the 3-D
    coordinates
  • mesh(xx, yy, zz) plots the surface as white
    facets outlined by colored lines
  • surf(xx, yy, zz) plots the surface as colored
    facets outlined by black lines

1-126
127
Designing a Cube Surface plot
1-127
128
Cube Surfaces
1-128
129
Simple Surface Plot
1-129
130
Compound Surface Plot
1-130
131
Using External Illumination
1-131
132
Designing a Cylinder Plot
1-132
133
Cylinder Plot
1-133
134
Sphere Plot
1-134
135
Bodies of Rotation
  • Created by rotating a linear curve about a
    specified axis
  • i.e. rotate z f(x) about the x or z axes (not
    y)
  • Rotate z f(x) about the x-axis
  • y r cos(?), z r sin(?)
  • Rotate z f(x) about the z-axis
  • x r cos(?), y r sin(?)

1-135
136
Rotating About the X Axis
1-136
137
Rotating About the Z Axis
1-137
138
Bodies of Rotation
1-138
139
Rotating Arbitrary Shapes
1-139
140
General Rotation TechniquesRotating about an
Arbitrary Axis
  • Calculate the matrix that will place your axis of
    rotation along the x-axis
  • Transform x and z with that rotation
  • Rotate the results about the x-axis
  • Invert the transformation on the resulting surface

1-140
141
A Solid Disk
1-141
142
A Klein Bottle
1-142
143
11.5 Engineering ExampleVisualizing Geographic
Data
  • Two files of data
  • atlanta.txt presents streets of Atlanta
  • ttimes.txt travel times between suburbs and city
  • Analyzing the Data
  • Determine the file format
  • Discern the street map file content
  • Discern the travel time file content

1-143
144
Map of Atlanta
1-144
145
Multimedia CS2 in Java
  • Driving question How did the wildebeests
    stampede in The Lion King?
  • Spring 2005 31 students, 75 female, 91 success
    rate.

146
Connecting to the WildebeestsIts all about data
structures
147
Syllabus
  • Introduction to Java and Media Computation
  • Manipulating turtles, images, MIDI, sampled
    sounds.
  • Insertion and deletion (with shifting) of sampled
    sounds (arrays).
  • Structuring Music
  • Goal A structure for flexible music composition
  • Put MIDI phrases into linked list nodes.
  • Use Weave and Repeat to create repeating motifs
    as found in Western Music
  • At very end, create a two-branched list to start
    on trees.

Swan
Canon
Fur Elise
Bells
148
HW2 Create a collage, but must use turtles
149
Syllabus (Continued)
  • Structuring Images
  • Using linearity in linked list to represent
    ordering (e.g., left to right)
  • Using linearity in linked list to represent
    layering (as in PowerPoint)
  • Mixing positioned and layered in one structure,
    using abstract super classes.
  • Structuring a scene in terms of
    branchesintroducing a scene graph (first tree)
  • (Well see these slides as an example later.)

150
Syllabus (Contd)
  • Structuring Sound
  • Collecting sampled sounds into linked lists and
    trees, as with images.
  • But all traversals are recursive.
  • Use different traversals of same tree to generate
    different sounds.
  • Replace a sound in-place

Original
Scale the children
Scale the next
151
Syllabus (contd)
  • Generalizing lists and trees
  • Create an abstract class Linked List Node
    (LLNode) on top of the sound and image class
    hierarchies
  • Make all image and sound examples work the same

abstract LLNode Knows next Knows how to do all
basic list operations
152
Syllabus (Contd)
JFrame
  • GUIs as trees
  • We introduce construction of a Swing frame as
    construction of a tree.
  • Different layout managers are then different
    renderers of the same tree.

JPanel
JPanel
JButton Make a picture
JLabel This is panel1!
JButton Make a sound
153
Syllabus (contd)
  • Lists that Loop
  • Introduce circular linked lists as a way of
    create Mario-Brothers style cel animations.
  • Introduce trees that loop as a way of introducing
    graphs.

gal1-rightface.jpg
gal1-rightface.jpg
gal1-right1.jpg
gal1-right2.jpg
154
Syllabus (contd)
  • Introducing Simulations
  • Introduce continuous and discrete event
    simulations, and Normal and uniform probability
    distributions
  • We do wolves and deer,disease propagation,politi
    cal influence.
  • Create a set of classes for simulation, then
    re-write our simulations for those classes.
  • Writing results to a file for later analysis
  • Finally, Making the Wildebeests and Villagers
  • Mapping from positions of our turtles to an
    animation frame.
  • Creating an animation from a simulation.

155
HW7 Simulate European emigration to America
  • Students are required to try several different
    scenarios, aiming for historical accuracy.
  • Counts of Europeans, Americans, and in-transit
    per year are written to a file for graphing in
    Excel
Write a Comment
User Comments (0)
About PowerShow.com