Docstoc

An Introduction To Technical Problem Solving

Document Sample
An Introduction To Technical Problem Solving Powered By Docstoc
					An Introduction To
Technical Problem Solving
with MATLAB v.7
        Jon Sticklen, PhD
       M. Taner Eskil, PhD
Introduction
          Chapter 1
Introduction

 What is Technical Problem Solving?
 The Path to Becoming a Good Technical
 Problem Solver
 What You Must Do to Master the Material



         Intro to Technical Problem Solving with MATLAB v.7
                                                              3
1-1 What is Technical Problem
Solving?
 Good common sense applied to technical
 problems
 Quantitative in nature
 Basis for making many decisions
 Rooted in numerical calculations
 Decompose the problem
 Mainstay of what an engineer does
         Intro to Technical Problem Solving with MATLAB v.7
                                                              4
1-2 The Path to Becoming a
Good Technical Problem Solver
 Master the conceptual subject matter of a
 given technical area
   Demonstrate what you have learned
 Master the tools of the trade
   MATLAB
   Mathematica
   MathCad

          Intro to Technical Problem Solving with MATLAB v.7
                                                               5
1-3 What You Must Do to Master
the Material
 Be prepared to spend substantial time
 learning this material
 Read assigned sections of the text with
 MATLAB at your side
 Work the problems hands-on

          Intro to Technical Problem Solving with MATLAB v.7
                                                               6
A Framework for
Technical Problem Solving
         Chapter 2
A Framework for Technical
Problem Solving

 Steps in a Framework for Technical
 Problem Solving
 An Example Using the Framework




         Intro to Technical Problem Solving with MATLAB v.7
                                                              8
2-1 Steps in a Framework for
Technical Problem Solving
 Step 1: Refine and Structure
   Arrive at a precise problem statement
   Give the problem initial structure:
     Problem inputs
     Computational output
 Step 2: Make a sketch or diagram
   Visualize the physical situation

          Intro to Technical Problem Solving with MATLAB v.7
                                                               9
2-1 Steps in a Framework for
Technical Problem Solving
 Step 3: Assemble and Organize
   What do you need to know to solve the
   problem?
   Get the needed information:
     Internet search engines such as Yahoo or Google
     Library
 Step 4: Simplify
   Find if there are suitable approximations
          Intro to Technical Problem Solving with MATLAB v.7
                                                               10
2-1 Steps in a Framework for
Technical Problem Solving
 Step 5: Decompose
   Simpler problems
   Reduce the complexity of the solution
 Step 6: Dimensional Analysis
   Are the mathematical relationships you intend
   to apply in your solution flawed?
   Substitute the units for each variable and
   algebraically simplify
          Intro to Technical Problem Solving with MATLAB v.7
                                                               11
2-1 Steps in a Framework for
Technical Problem Solving
 Step 7: Compute and Discuss
   Perform the computations needed to obtain a
   solution
     Use a computational tool such as MATLAB
   Examine and understand the results
     Be ready to explain them!




          Intro to Technical Problem Solving with MATLAB v.7
                                                               12
2-2 An Example Using the
Framework
 Problem:
   What is the optimum firing angle we should set
   for a catapult whose purpose is to hurl hay
   bales to a herd of starving caribou, given the
   initial velocity of hay bales as they exit the
   catapult?




            Intro to Technical Problem Solving with MATLAB v.7
                                                                 13
2-2.1 Refine and Structure
 Clarify:
   Think about the problem
   The ultimate source of information is the person setting
   the problem
 Refine:
   What is the firing angle of a catapult in order to hurl
   projectiles a maximum horizontal distance given the
   initial velocity of the object?
 What are the Input(s) and Output(s)?
   Initial speed, angle, maximized distance

            Intro to Technical Problem Solving with MATLAB v.7
                                                                 14
2-2.2 Sketch or Diagram
 What is the firing angle measured from the
 horizontal we should set for a catapult to hurl
 projectiles a maximum horizontal distance given
 the initial velocity of the object?




           Intro to Technical Problem Solving with MATLAB v.7
                                                                15
2-2.3 Background Knowledge
 For our example:
   General knowledge of physics
   General knowledge of one way in which
   optimizing problems may be solved
 Seek the value of the firing angle f that
 maximizes the total horizontal distance D
 traveled given an initial speed of the hay
 bale as it comes out of the catapult
          Intro to Technical Problem Solving with MATLAB v.7
                                                               16
2-2.4 Assumptions and
Approximations
 Many times in technical problem solving, the path
 to a solution leads to making assumptions about
 the problem and then solving the simplified
 version of the problem.
   Negligible air resistance
   No difference between a hay bale and a snowball
 Be aware of the assumptions you are making and
 communicate them to the person who originally
 set the problem for you.
   Importance of good documentation
           Intro to Technical Problem Solving with MATLAB v.7
                                                                17
2-2.5 Decomposing /Recursive
Structuring
 Break the problem into pieces, each with its
 own well defined input and output
 Develop technical solutions for each piece
 Work backwards to find what you need



          Intro to Technical Problem Solving with MATLAB v.7
                                                               18
2-2.6 Dimensional Analysis




       Intro to Technical Problem Solving with MATLAB v.7
                                                            19
2-2.7 Putting It All Together
  f (degrees)               0          10         20        30           40
  Unit Distance (feet)       0.0000    0.0107     0.0201    0.0271       0.0308
  f (degrees)               90         80         70        60           50
  Unit Distance (feet)      0.0000     0.0107     0.0201    0.0271       0.0308




                    Intro to Technical Problem Solving with MATLAB v.7
                                                                                  20
2-2 Synopsis

 Identify input and output variables correctly
 Create a sketch of the physical situation
 Generalize the problem
 Apply general background knowledge
 General approach to optimization problems



          Intro to Technical Problem Solving with MATLAB v.7
                                                               21
MATLAB Basics: Scalars
         Chapter 3
Scalars

 The First Time You Bring Up MATLAB
 MATLAB as a Calculator for Scalars
 Fetching and Setting Scalar Variables
 MATLAB Built-in Functions, Operators,
 and Expressions
 Problem Sets for Scalars

          Intro to Technical Problem Solving with MATLAB v.7
                                                               23
3-1 The First Time You Bring Up
MATLAB
Basic windows in MATLAB are:
  Command - executes single-line commands
  Workspace - keeps track of all defined variables
  Command History - keeps a running record of all single
  line programs you have executed
  Current Folder - lists all files that are directly available for
  MATLAB use
  Array Editor - allows direct editing of MATLAB arrays
  Preferences - for setting preferences for the display of
  results, fonts used, and many other aspects of how
  MATLAB looks to you

                Intro to Technical Problem Solving with MATLAB v.7
                                                                     24
3-2 MATLAB as a Calculator for
Scalars
 A scalar is simply a number…



 In science the term scalar is used as opposed to a vector,
 i.e. a magnitude having no direction.
 In MATLAB, scalar is used as opposed to arrays, i.e. a
 single number.
 Since we have not covered arrays (tables of numbers)
 yet, we will be dealing with scalars in MATLAB.

             Intro to Technical Problem Solving with MATLAB v.7
                                                                  25
Using the Command History
Window




       Intro to Technical Problem Solving with MATLAB v.7
                                                            26
3-3 Fetching and Setting Scalar
Variables
 Think of computer
 variables as named
 containers.
 We can perform 2
 types of operations
 on variables:

  we can set the value held in the container: x = 22
  we can look at the value held in the container: x
           Intro to Technical Problem Solving with MATLAB v.7
                                                                27
The Assignment Operator (=)
 The equal sign is the assignment operator in
 MATLAB.
           >> x = 22
 places number 22 in container x
 How about:
           >> x = x + 1
 Note the difference between the equal sign in
 mathematics and the assignment operator in
 MATLAB!
           Intro to Technical Problem Solving with MATLAB v.7
                                                                28
3-3.2 An Example - Setting
Variables for the Hay Bale Problem
 >> clear
 >> accelGravity = 32; % units: ft/sec/sec
 >> speedInitial = 50; % units: ft/sec
 >> phi = 10; % units: degrees

  clear deletes variables from workspace, you
  should use it before starting new work
  The percent symbol is used for putting reminders
  (comments) for ourselves, ignored by MATLAB
  Command lines ending with semicolon do not
  display the results.
                 Intro to Technical Problem Solving with MATLAB v.7
                                                                      29
3-4 MATLAB Built-in Functions,
Operators, and Expressions
 MATLAB comes with a large number of built-
 in functions (e.g.. sin, cos, tan, log10, log, exp)
 A special subclass of often-used MATLAB
 functions is called operators
    Assignment operator (=)
    Arithmetic operators (+, -, *, /, ^)
    Relational operators (<, <=, = =, ~=, >=, >)
    Logical operators (&, |, ~)


             Intro to Technical Problem Solving with MATLAB v.7
                                                                  30
Example – Arithmetic Operators




       Intro to Technical Problem Solving with MATLAB v.7
                                                            31
Example – Relational and
Logical Operators




       Intro to Technical Problem Solving with MATLAB v.7
                                                            32
3-4.2 Rules for Forming
Expressions
 MATLAB expressions consist of:
   Numerical values or variables
   Logical values or variables
   Legal applications of MATLAB functions or
   operators
   A combination of MATLAB expressions
 What is the error in the following MATLAB
 expression?
    >> sin(pi/2, pi/8)
            Intro to Technical Problem Solving with MATLAB v.7
                                                                 33
Order of Precedence
 If two operators are at
 the same level of
 precedence, the
 evaluation is carried out
 from left to right
 An Example – Compute




 for x = 4, y = 2
            Intro to Technical Problem Solving with MATLAB v.7
                                                                 34
Applying Scalar Computations to
a Problem




       Intro to Technical Problem Solving with MATLAB v.7
                                                            35
Synopsis for Chapter 3
A MATLAB variable can be thought of as a named container. The value of a
MATLAB variable then is the contents of the box.
Setting the variable value is done using the assignment operator; fetching the
value of a variable is done by typing the name of the variable.
In MATLAB the type of a variable is defined by the way the variable is used.
Scalars are simple numbers.
Logical values can be TRUE (any non-zero number) or FALSE (0).
MATLAB operators are a special subclass of MATLAB built-in functions.
Arithmetic operators take numerical variables as input and output a numerical
result.
Relational operators take numerical variables as input and output a logical
result.
Logical operators take logical variables as input and output a logical result.
MATLAB expressions are blueprints for performing computations.
                  Intro to Technical Problem Solving with MATLAB v.7
                                                                            36
Saving MATLAB Work
        Chapter 4
Saving MATLAB Work

 The MATLAB “Current Directory”
 Saving MATLAB Commands in Script
 Files
 Saving MATLAB Commands in User-
 Defined Function Files
 Testing and Debugging MATLAB Script
 and Function Files
 Problem Sets for “Saving Your Work”
        Intro to Technical Problem Solving with MATLAB v.7
                                                             38
4-1 The MATLAB Current
Directory
MATLAB starts
up with the
default folder
connected
It is the default folder MATLAB will save files
It is the first folder MATLAB will attempt to load files
It may be changed interactively using the Current
Directory Window or built-in commands

            Intro to Technical Problem Solving with MATLAB v.7
                                                                 39
4-2 Saving MATLAB Commands
in Script Files
 Script files are lines of code just like you
 would type in to the Command Window
 It is good programming practice to include
 comments for:
   The location of the file
   Variables used in the script but defined outside
   Results produced by the script
   Units of values calculated in the script
          Intro to Technical Problem Solving with MATLAB v.7
                                                               40
An Example – The Water Tower
Problem
 compute water tower cost
 and volume
 cylinder caped by
 hemisphere
 diameter and height of
 cylinder known
 known cost/m2 for
 hemisphere and for
 cylinder


            Intro to Technical Problem Solving with MATLAB v.7
                                                                 41
Synopsis for MATLAB Scripts
 A script file consists of groups of MATLAB
 commands bundled together into a module
 Scripts files have a DOT-M extension
 When executing inside a script file, all
 variables in the workspace are available
 Variables created in a script are available at
 the Command Window and in other scripts
 Making a sketch of a problem is important
 in making the problem context concrete
          Intro to Technical Problem Solving with MATLAB v.7
                                                               42
4-3 Saving MATLAB Commands
in User-Defined Function Files
 Scripts - these are lines of code exactly like
 you could type in to the command window
 Functions - are “computational boxes.” You
 give them a set of input values, and they
 calculate a set of output values. Purpose of
 functions is the same as the purpose of scripts
 +
            modularize your code
           Intro to Technical Problem Solving with MATLAB v.7
                                                                43
Central Points…
  The only way of getting a variable‟s value into a
  function is for that variable to be input to the
  function.
  The only way of getting a value out of a function is
  for that variable to be output from the function.
  A variable used inside a function that is not an input
  or an output variable is not visible outside the
  function.
An example:
       >> x = pi;
       >> y = sin(x)
             Intro to Technical Problem Solving with MATLAB v.7
                                                                  44
Syntax of a User Defined Function

 Functions are saved in DOT M files - just
 like the script files
 Same rules for the connected directory
 applies
 First line of the file defines
   Name of the function
   Input variable(s)
   Output variable(s)
          Intro to Technical Problem Solving with MATLAB v.7
                                                               45
Defining a function – the first line
  function <outputVars> = <function name>(<inputVars>)


                                                      0, 1, or more vars. If 0,
           0, 1, or more vars. If                     then the enclosing parens
           more than 1, put in                        are not needed.
           square brackets.
                                    required

                                     You choose the name - see text or
                                     ML help for valid name - mostly
  Keyword - has to be                just start with a regular
  exactly as appears                 character and have no spaces.




                 Intro to Technical Problem Solving with MATLAB v.7
                                                                                  46
Linkage Between Actual and
Formal Parameters
                            ...
     calling program:
                            z = myFun3(a,b)

                            ...
    the function called:
                function out33 = myFun3(x,y)

When the function myFun3 is “called”…
1. The formal input variables (x,y) take the values given in the
   calling line (a,b)
2. The function “runs”
3. The output variables in the function are given back to the calling
   program’s variable.
                    Intro to Technical Problem Solving with MATLAB v.7
                                                                         47
Comments in Functions
 There are no uniformly agreed upon rules for
 inserting comments into functions
 It is always good programming practice to include
 comment lines indicating:
   the purpose of the function
   the inputs to the function
   the outputs from the function
   any assumptions


            Intro to Technical Problem Solving with MATLAB v.7
                                                                 48
Examples
function <outputVars> = <function name>(<inputVars>)


For each of the following function definitions,
  how many input and output variables are
  there?
   function x = myFun1
   function z = myFun2(y)
   function out33 = myFun3(x,y)
   function [a,b] = myFun4(q,r)
             Intro to Technical Problem Solving with MATLAB v.7
                                                                  49
Examples




      Intro to Technical Problem Solving with MATLAB v.7
                                                           50
Examples




      Intro to Technical Problem Solving with MATLAB v.7
                                                           51
Synopsis for User-Defined
Functions
 The workspace of a function is insulated from the outside.
 When a MATLAB function is called, a linkage is made
 between the actual parameters in the call and the formal
 parameters in the function definition.
 The number of actual input parameters must be the same as
 the number of formal input parameters. This is also valid
 for the output parameters.
 The first line of a MATLAB function begins with the
 keyword function, and the rest of the first line looks like an
 assignment statement.
             Intro to Technical Problem Solving with MATLAB v.7
                                                                  52
4-4 Testing and Debugging
MATLAB Script and Function Files
Types of errors in programs:
  Syntax errors
     Results from incorrect application of MATLAB rules
     MATLAB aborts the computation and points of the
     error
  Runtime errors
     Results from incorrect logic and MATLAB not doing
     what you intend
     For this type error MATLAB debugging facilities are
     useful
             Intro to Technical Problem Solving with MATLAB v.7
                                                                  53
Examples




      Intro to Technical Problem Solving with MATLAB v.7
                                                           54
Examples




      Intro to Technical Problem Solving with MATLAB v.7
                                                           55
Synopsis for Debugging
 Identify the set of inputs you will use for the test
 Determine what you expect for each of the test
 input sets to produce
 Compare what you expect to what MATLAB
 produces to identify runtime errors in the function
  Identify and correct the line(s) of code that are
 causing the runtime error

            Intro to Technical Problem Solving with MATLAB v.7
                                                                 56
Vector Operations
         Chapter 5
Vector Operations

 Vector Creation
 Accessing Vector Elements
 Row Vectors and Column Vectors, and the
 Transpose Operator
 Vector Built-in Functions, Operators, and
 Expressions


         Intro to Technical Problem Solving with MATLAB v.7
                                                              58
5-1 Vector Creation
 Vectors are defined in square brackets;
     temperaturesMonThu = [32 31 29 33];
     temperaturesFriSat = [35 33];
 You can concatenate a vector with a scalar;
     temperaturesFriSun = [35 33 27];
 or concatenate 2 vectors;
     weeklyTemperatures = [temperaturesMonThu, temperaturesFriSun];
 To find the size of a vector, we use length;
     numTemperatures = length(weeklyTemperatures);
 We could find the average temperature by typing;
     avgTemperature = mean(dailyTemperatures)
 or by using sum and length;
 totalTemperature = sum(dailyTemperatures)/length(dailyTemperatures);
               Intro to Technical Problem Solving with MATLAB v.7
                                                                        59
Some Useful Vector Functions
 brackets (e.g. [27 36 41]): Creates vectors.
 colon operator (e.g. [0:5:30]): Creates linearly spaced vectors.
 linspace (e.g. linspace(0,100,21)): Creates linearly spaced vectors.
 length (e.g. length([0:5:30])): Finds the length of a vector.
 zeros (e.g. zeros(1,5)): Creates vectors filled with zeroes.
 ones (e.g. ones(1,5): Creates vectors filled with ones.
 sum (e.g. sum([5 3 6 2])): Sums up the contents of a vector.
 sort (e.g. sort([5 3 6 2])): Sorts the contents of a vector.
 mean (e.g. mean([5 3 6 2])): Finds the average of contents.

                 Intro to Technical Problem Solving with MATLAB v.7
                                                                        60
5.2 – Accessing Vector Elements –
Examples
1. Create a row vector x consisting of the numbers in the ordered
   set: {1 4 7 10} using the colon operator.
       x = [1:3:10]

2. Set a variable y to be the length of x.
       y = length(x)

3. Set variable y to be the 1st element of x.
       y = x(1)

4. Set variable y to be the 1st, 2nd, and 3rd elements of x.
       y = x([1,2,3]) OR y = x(1:3)


                  Intro to Technical Problem Solving with MATLAB v.7
                                                                       61
Accessing Vector Elements –
Example cont’d.
5.   Set variable y to be the 3rd through the last element of x - and do so
     such that your solution works no matter how long x is.
         y = x(3:end)

6.   Set variable y to be the next-to-last and last element of x - and do so
     such that your solution works no matter how long x is.
         y = x([end-1,end])

7.   Change the 2nd element of x to be 3.
         x(2) = 3

8.   Change the 2nd element of x to be 102 and the 4th element of x be
     205.
         x([2,4]) = [102, 205]

                    Intro to Technical Problem Solving with MATLAB v.7
                                                                           62
Synopsis for Fetching and Setting
Elements in Vectors
 Access to whole vector is similar to scalar access.
 Accessing element(s) in a vector is done by indexing into
 the vector.
 To delete element(s) in a vector, empty square brackets are
 used.
 To find the length of a vector V, use the length built-in
 function length(V).
 When setting elements of a vector, the number of elements
 being set must be equal to the number of elements in the
 vector on the right hand side of the assignment operation.
 The exception is that a scalar on the right-hand side can be
 used to set multiple vector elements.
             Intro to Technical Problem Solving with MATLAB v.7
                                                                  63
5-3 Row Vectors and Column
Vectors, and the Transpose Operator
 Row and column vectors are represented as single
 rows and columns of values, respectively.
 When creating a column vector with square
 brackets, you may use the semicolon operator:
    temp = [35; 33; 27];
 or you may use the transpose operator;
    temp = [35 33 27]‟;
 When creating an equally spaced column vector,
 you need to use the transpose operator;
    springConstants = [10:10:100]‟;
    springConstants = linspace(10,100,10)‟;
             Intro to Technical Problem Solving with MATLAB v.7
                                                                  64
5-4 Vector Built-in Functions,
Operators, and Expressions



        Intro to Technical Problem Solving with MATLAB v.7
                                                             65
Sample Problem – Vector Built-
in Functions




       Intro to Technical Problem Solving with MATLAB v.7
                                                            66
Sample Problem – Vector
Arithmetic Operators




       Intro to Technical Problem Solving with MATLAB v.7
                                                            67
Sample Problem – Vector
Arithmetic Operators




       Intro to Technical Problem Solving with MATLAB v.7
                                                            68
Sample Problem – Vector
Arithmetic Operators




       Intro to Technical Problem Solving with MATLAB v.7
                                                            69
Vector Relational Operators

 Think of them as comparing numbers…
          <, >, = =, >=, <=
 A relational operator can be used to
 compare the values of two variables
                a>b
 But… remember MATLAB is for matrices
    what are you testing?
        Intro to Technical Problem Solving with MATLAB v.7
                                                             70
What are you testing?
 Number (scalar) vs. Number
 Number vs. Vector (or Matrix)
   A scalar is compared to each element of the vector…
            5<[1:10]
 Vector vs. Vector
   Each corresponding element of the two vectors is
   compared…
       [1:10]<=[10:-1:1]

           Intro to Technical Problem Solving with MATLAB v.7
                                                                71
Sample Problem – Vector
Relational Operators




       Intro to Technical Problem Solving with MATLAB v.7
                                                            72
Vector Logical Operators
 They operate on the results of relational operators
 How many elements in vector x are in range
 (6,10)?
 How many elements in x are
   … greater than 6
   AND
   … less than 10?
 We use logical operators…
   AND (&), OR (|), NOT (~)
   any, all

           Intro to Technical Problem Solving with MATLAB v.7
                                                                73
Sample Problem – Vector
Logical Operators




       Intro to Technical Problem Solving with MATLAB v.7
                                                            74
Synopsis for Vector Operators
 There are functions that work in a cell-by-cell fashion (like sin) and functions
 that aggregate (like sum).
 Cell-by-cell vector operators apply the indicated operation to the
 corresponding elements of the two vectors.
 For cell-by-cell operations, the two arguments must be the same type of vector
 (row or column) and be of the same length, or one of the arguments must be a
 scalar.
 Cell-by-cell vector operators include the classes (assignment, colon and
 transpose operators), the vector arithmetic cell-by-cell operators (Table 5-2),
 the vector relational operators (Table 5-4), and vector cell-by-cell logical
 operators (Table 5-5).
 Logical computations are extended via built-in logical functions (Table 5-6).
 The built-in logical function find is useful because it enables a type of content
 addressing.
 The operator precedence table was updated to include new possibilities (Table
 5-7).



                 Intro to Technical Problem Solving with MATLAB v.7
                                                                                75
2-D Plotting and Help in
MATLAB
          Chapter 6
2-D Plotting and Help in
MATLAB
 Using EZPLOT to Plot Functions
 Using Vectors to Plot Numerical Data
 Overlay plots and subplots
 Other 2-D plot types in MATLAB
 Problem Sets for 2-D Plotting



         Intro to Technical Problem Solving with MATLAB v.7
                                                              77
6-1 Using EZPLOT to Plot
Functions




       Intro to Technical Problem Solving with MATLAB v.7
                                                            78
Getting Help

 You can‟t possibly learn everything there is
 to know about MATLAB,
      … and you don‟t need to.
 It is crucial to develop the ability to
 augment your knowledge in MATLAB
 toward accomplishing a given task.


          Intro to Technical Problem Solving with MATLAB v.7
                                                               79
Getting Help cont’d




       Intro to Technical Problem Solving with MATLAB v.7
                                                            80
Getting Help cont’d
 Click the tab in the navigation pane labeled
 Search.
 Then type into the Search field the name ezplot.




           Intro to Technical Problem Solving with MATLAB v.7
                                                                81
Using EZPLOT to Plot Functions
 There are three forms of ezplot:
   f(x)                e.g., f(t) = 3e-2tcos(5t)
            ezplot('3*exp(-2*t)*cos(5*t)')
   f(t), g(t)          e.g., f(t) = 3t2 + 2; g(t) = sin(5t)
            ezplot('3*t^2 + 2', 'sin(5*t)')
   f(x,y) = 0          e.g., f(x,y) = 3xy + y2 + 55 = 0
    ezplot('3*x*y + y^2 + 55',[-30,30,-20,20])

            Intro to Technical Problem Solving with MATLAB v.7
                                                                 82
Sample Problem - EZPLOT




      Intro to Technical Problem Solving with MATLAB v.7
                                                           83
Graphing with MATLAB
 Use ezplot to make a quick and dirty chart of
 functions.
 Optional arguments allow changing the default
 functional domain [-2π, 2π].
 Use xlabel, ylabel, and title built-in functions to
 refine labeling the plots made by ezplot.
 When needed, use grid to activate a grid on a plot
 created.
 If you would like to keep the existing graph and
 generate a new one, use figure.
           Intro to Technical Problem Solving with MATLAB v.7
                                                                84
6-2 Using Vectors to Plot
Numerical Data
 Mostly from observed data - your goal is to understand the
 relationship between the variables of a system.
  Speed (mi/hr)                20 30 40           50      60     70
  Stopping Distance (ft) 46 75 128 201 292 385

 Determine the independent and dependent variables and plot:
           speed = 20:10:70;
           stopDis = [46,75,128,201,292,385];
           plot(speed, stopDis, '-ro') % note the „-ro‟ switch
 Don‟t forget to properly label your graphs:
           title('Stopping Distance versus Vehicle Speed', 'FontSize', 14)
           xlabel('vehicle speed (mi/hr)', 'FontSize', 12)
           ylabel('stopping distance (ft)', 'FontSize', 12)
           grid on


                  Intro to Technical Problem Solving with MATLAB v.7
                                                                             85
Sample Problem – Plotting
Numerical Data




       Intro to Technical Problem Solving with MATLAB v.7
                                                            86
Plotting Functions Numerically
 ezplot is a great tool for plotting functions, but it has several
 disadvantages:
     it doesn‟t provide as much control as plot, e.g. dotted lines.
     you must fill in values for any constants, e.g.

 When you need more control, plot numerically with plot:
       d = 4;
       h = linspace(1,10); % Step 1 - create vector for independent variable
       V = pi*d^2/4*h; % Step 2 – compute vector for dependent variable
       plot(h,V,'-r') % Step 3 - plot and label
       xlabel('height (m)', 'FontSize', 12)
       ylabel('Volume (m^3)', 'FontSize', 12)
       title('Volume of a cylinder versus its height','FontSize', 14)
       grid on

                  Intro to Technical Problem Solving with MATLAB v.7
                                                                               87
Sample Problem – Plotting
Functions Numerically
A function G(x,y,z) of three independent variables is
  defined as:




Write a function that takes no inputs or outputs but
 creates a plot of G(x,y,z), subject to:
             0.1 < x < 4
             y = 5, z = 3

             Intro to Technical Problem Solving with MATLAB v.7
                                                                  88
Synopsis for ezplot and plot
 The first argument to plot should be the vector of values
 for the independent variable (going on the x-axis); the
 second argument should be the vector of values for the
 dependent variable (going on the y-axis).
 An optional third argument plot is the line spec which
 specifies the type of line used (solid, dotted, etc.), the
 color of the line used, and the type of data marker (if any).
 For plotting numerical data from experimentation or
 observation, use data markers.
 For plotting numerical data that are computed from a
 mathematical relationship, data markers must not be used.

             Intro to Technical Problem Solving with MATLAB v.7
                                                                  89
   6-3 Overlay Plots and Subplots




Allows putting more than one                    For multiple dependent variables
relationship directly into the same             whose data are not of the same type,
plotting window.                                e.g. acceleration, speed and distance
Two key functions: hold and legend              Key function to learn: subplot


                       Intro to Technical Problem Solving with MATLAB v.7
                                                                                        90
Sample Problems – Overlay Plots
and Subplots




       Intro to Technical Problem Solving with MATLAB v.7
                                                            91
Sample Problems – Overlay Plots
and Subplots




       Intro to Technical Problem Solving with MATLAB v.7
                                                            92
Synopsis for Overlay Plots and
Subplots
 Overlay plots are used to show a family of parameterized
 results
 hold on is the key MATLAB command needed to turn on
 overlays
 Subplots are used to display plots of different independent
 variables usually from one experimental data set or from
 one set of equations for a single physical system.
 subplot is the key MATLAB command needed to identify
 the target for a created plot.


             Intro to Technical Problem Solving with MATLAB v.7
                                                                  93
Arrays
Chapter 7
So far we have learned…

 Using MATLAB for scalar computations (Ch. 3)
 Saving your work in MATLAB user-defined
 functions (Ch. 4)
 Debugging MATLAB functions (Ch. 4)
 Using MATLAB for vector operations (Ch. 5)
 Using MATLAB to make 2-D plots (Ch. 6)
 Using the MATLAB Help facility to let you
 extend what you know (Ch. 6)
          Intro to Technical Problem Solving with MATLAB v.7
                                                               95
The Pattern…

 Scalars – numbers
 MatLab Vectors – Ordered, linear groupings
 of scalars
 Simple extension – MatLab Arrays
   Instead of having a one-dimensional grouping
   of scalars as in vectors, MATLAB arrays are
   two-dimensional groups of scalars.

          Intro to Technical Problem Solving with MATLAB v.7
                                                               96
7-1 Array Creation




       Intro to Technical Problem Solving with MATLAB v.7
                                                            97
Creating Arrays
 A semicolon as punctuation in the square bracket
 operator tells MATLAB to start a new row
  >> A = [1, 2, 3; 10, 20, 30]
 linspace and the colon operator can be used to
 create vectors that are subsequently composed into
 an array:
  >> A = [1:3:15; linspace(0,1,5)]
or…
  >> A = [(1:3:15)', linspace(0,1,5)']

             Intro to Technical Problem Solving with MATLAB v.7
                                                                  98
Things to know…
 A typical mistake – trying to concatenate incompatible
 vectors:
 >> B1 = [1, 2, 3];
 >> B2 = [10, 11];
 >> stackedUpDown = [B1; B2]
 ??? Error using ==> vertcat
 All rows in the bracketed expression must have
 the same number of columns.


 Creating an array whose elements are all value 0 (or 1) :
 >> twoByFourZeros = zeros(2,4)

              Intro to Technical Problem Solving with MATLAB v.7
                                                                   99
Synopsis for Creating Arrays
 Semicolon punctuation inside the square bracket operator
 indicates to MATLAB that a new row is to be created.
 When concatenating arrays, their dimensions must be
 consistent.
 ones and zeros are built-in functions that create arrays
 whose elements are all value 1 or all value 0, respectively.
 ones and zeros take two arguments: the number of rows
 and the number of columns in the array that will be
 created.

             Intro to Technical Problem Solving with MATLAB v.7
                                                                  100
7-2 Accessing Array Elements




       Intro to Technical Problem Solving with MATLAB v.7
                                                            101
Fetching Elements
 Create an array A by the following:
  >> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]
 Pull out the value of the element at the second row, third column:
  >> x = A(2,3)
 Fetch the second and third elements in the second row of A:
  >> V = A(2, [2,3])
 Extract the entire second column:
  >> X2 = A(:, 2)
 Fetch the entire third and fourth columns:
  >> partOfB = A(:, [3,4])
 Fetch the first and second elements in the second and third columns:
  >> anotherPartOfB = A([1,2], [2,3])


                  Intro to Technical Problem Solving with MATLAB v.7
                                                                        102
Fetching Elements cont’d




  How would you address to number 0?

  Row first, column next;
                     >> A(2,4)

  How about 2?
                       >> A(3,2)
            Intro to Technical Problem Solving with MATLAB v.7
                                                                 103
Fetching Elements cont’d



How can we extract the collection of numbers in the dotted box?
That is, the numbers in the 1st through 3rd rows, 2nd through 4th
columns…
Specify the row and column numbers by counting them…
                  A(1:3, 2:4)

               Intro to Technical Problem Solving with MATLAB v.7
                                                                    104
Setting Elements
 Create an array A by the following:
  >> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]
 Set the element at row two and column 4 to 100:
  >> A(2,4) = 100;
 Create a new array B that is identical to modified A, except that the
 second and third columns are interchanged.
  >> B = A;
  >> B(:,[2,3]) = A(:, [3,2])
 The shape of the array to be set must be the same as the shape of the
 array that holds the new values.


                 Intro to Technical Problem Solving with MATLAB v.7
                                                                         105
Built-in Functions end and size
 Create an array A by the following:
  >> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]
 Replace the last and next to last row/column elements with [100, 101;
 200, 201]
  >> A(end-1:end,end-1:end) = [100, 101; 200, 201]
 For vectors, we had length to return the number of elements.
 For arrays, size built-in function is used:
  >> [numRows, numCols] = size(A)



                Intro to Technical Problem Solving with MATLAB v.7
                                                                     106
Synopsis for Setting Elements
 Array access operations (fetch and set) are directly
 analogous to vector access operations.
 For array setting, the part of an array to be set and the
 elements which will be inserted must be the same shape.
 The colon may be used as an index element to indicate all.
 end is used in array access as it is used in vector access.
 To determine the number of rows and columns in an array,
 use size.

              Intro to Technical Problem Solving with MATLAB v.7
                                                                   107
7-3 Transpose Applied to Arrays




       Intro to Technical Problem Solving with MATLAB v.7
                                                            108
The Transpose Operator
 The transpose operator is used to flip an array.
 More formally, if A is an NxM vector, then A' will be an
 MxN array whose elements are defined by A'(i,j) = A(j,i).
 >> D = [1,2,3,4; 10,11,12,13; 20, 21,22,23]
 >> transposeD = D‟
 The effect of applying the transpose operator to an array is
 to flip rows and columns.
 What was a row is now a column, and what was a column
 is now a row.

              Intro to Technical Problem Solving with MATLAB v.7
                                                                   109
7-4 Array Built-in Functions,
Operators, and Expressions



       Intro to Technical Problem Solving with MATLAB v.7
                                                            110
Built-in Functions and Operators
 The same types in Vectors exist – with new
 possibilities
 >> D = [1,10; 100,110]
 >> sumOverColumns = sum(D,1)
 >> sumOverRows = sum(D,2)




         Intro to Technical Problem Solving with MATLAB v.7
                                                              111
Cell-by-Cell Operators
 Arrays A and B are defined as:
 >> A = [2:4; 20:10:40]
 >> B = [1:3; 1:3]
 Find cell-by-cell product of A and B:
 >> A .* B
 Find A raised to the power B, cell-by-cell:
 >> A .^ B
 Find A/B, cell-by-cell:
 >> A ./ B
 A./B stands for          , whereas B./A stands for                ,
 cell-by-cell
              Intro to Technical Problem Solving with MATLAB v.7
                                                                       112
  Example Problem 1
  Cell-by-Cell Operators
  The ABC electronics factory makes four different items: a
    48-inch HDTV, a 32-inch regular TV, a computer called
    the M2 model, and a DVD player called the R2 model.

Compute:
(a) the total cost for materials used on
    all four product lines for each
    quarter and

(b) the total yearly cost for
    materials used in each of
    four product lines.

                     Intro to Technical Problem Solving with MATLAB v.7
                                                                          113
Example Problem cont’d
 Find by hand quarter 1 to material costs from
 the HDTV product line.
     532 * $892 = $474,544.
 Think through the problem statement.
 This problem is not conceptually difficult but is
 tedious.
 MATLAB provides a better way…


            Intro to Technical Problem Solving with MATLAB v.7
                                                                 114
Matrix Operators
   Matrix multiplication operation is defined as:



1. The number of columns in A must be equal to the
   number of rows in B. Otherwise, this is not a legal
   operation.
2. Assuming Rule 1 is met the number of rows in C will be
   equal to the number of rows in A.
3. Likewise, the number of columns in C will be equal to
   the number of columns in B.
              Intro to Technical Problem Solving with MATLAB v.7
                                                                   115
Matrix Multiplication


1   2          9         7                  (1,1)
                                          1*9 + 2*8              (1,2)
                                                               1*7 + 2*6
3   4
          X    8         6
                                 =          (2,1)
                                          3*9 + 4*8              (2,2)
                                                               3*7 + 4*6
    2X2               2X2                                              2X2
                                                25                19
                                 =              59                45

          Intro to Technical Problem Solving with MATLAB v.7
                                                                       116
Example Problem 2
Matrix Operators




       Intro to Technical Problem Solving with MATLAB v.7
                                                            117
  Revisiting Example Problem 1
  The ABC electronics factory makes four different items: a
    48-inch HDTV, a 32-inch regular TV, a computer called
    the M2 model, and a DVD player called the R2 model.

Compute:
(a) the total cost for materials used on
    all four product lines for each
    quarter and

(b) the total yearly cost for
    materials used in each of
    four product lines.

                     Intro to Technical Problem Solving with MATLAB v.7
                                                                          118
Example Problem cont’d




    ?                         =

        Intro to Technical Problem Solving with MATLAB v.7
                                                             119
Example Problem 3
Matrix Operators




       Intro to Technical Problem Solving with MATLAB v.7
                                                            120
Matrix Left Division
 A linear system of equations can be modeled as:




 In other words…

           Intro to Technical Problem Solving with MATLAB v.7
                                                                121
Matrix Left Division cont’d


  Can be solved for x as follows:


  Or in MatLab by left division:

        Intro to Technical Problem Solving with MATLAB v.7
                                                             122
Example Problem 4
Matrix Left Division
Jeanie, Juan, and Alexander each have some fruit. Each has a
   number of apples, oranges, and pears.
All apples have the same weight, all oranges have the same
   weight, and all pears have the same weight.
Jeanie has 3 apples, 2 oranges, and 1 pear. The total weight of
   fruit that Jeanie has is 52 ounces.
Juan has 2 apples, 3 oranges, and 1 pear. The total weight of
   fruit that Juan has is 50 ounces.
Alexander has 1 apple, 2 oranges, and 3 pears. The total
   weight of fruit that Alexander has is 56 ounces.

What is the weight of each apple, orange, and pear?
               Intro to Technical Problem Solving with MATLAB v.7
                                                                    123
Example Problem 5
Relational and Logical Operators


1.   Using the find function, find and display:
     a.   the row and column numbers of elements in A that are less than
          zero
     b.   elements that are less than zero
     c.   elements that are greater than -4 but less than 4
2. Using the all or any functions, determine:
     a.   if all elements in A are greater than -8
     b.   if any elements in A are less than -5
                   Intro to Technical Problem Solving with MATLAB v.7
                                                                        124
Synopsis
 Arrays are indexed by giving the row and column locations.
 All cell-by-cell operations are generalizations of the corresponding
 vector operation.
 Matrix multiplication can be very advantageous when the problem you
 are solving involves a sum of scalar multiplication operations.
 Matrix left division is often used to solve systems of linear
 simultaneous equations.
 Values in an array that meet some relational test may be extracted
 using find as an indexing term.
 Two output values are returned when the find function is applied to an
 array: a vector of row index values and a corresponding vector of
 column index values.
                Intro to Technical Problem Solving with MATLAB v.7
                                                                        125
Conditional and Iterative
    Programming
        Chapter 7
8-1 Program Flow

1. Straight Line Code


                                   One line of code after
                                   another… just in
                                   sequence. Also called
                                   “sequential code”.

         Intro to Technical Problem Solving with MATLAB v.7
                                                              127
Program Flow cont’d

2. Conditional Code



    NO              YES                Based on a test,
         test
                                       perform one alternative
                                       set of code and not
                                       another…

         Intro to Technical Problem Solving with MATLAB v.7
                                                              128
Program Flow cont’d

3. Iterative code
                                     Execute the same
                                     block of code
                                     again and again …

                       repeat…


          Intro to Technical Problem Solving with MATLAB v.7
                                                               129
Synopsis for Program Flow
Types
 There are three major types of program control: straight
 line control, conditional control, and iterative control.
 Programming constructs for conditional control and
 iterative control should be considered “modules,” meaning
 there is one point of entrance into the construct and one
 point of exit.
 Straight line code executes in the order it is written in a
 program.
 Conditional code executes one alternative of a number of
 possibilities, selecting the alternative to run based on a
 relational/logical test of program variables.
 Iterative code executes the same block of code a number of
 times.
             Intro to Technical Problem Solving with MATLAB v.7
                                                                  130
8-2 Iterative Program Flow:
FOR
 General form:




 A FOR loop must end with a line containing
 end.
           Intro to Technical Problem Solving with MATLAB v.7
                                                                131
Questions for the Iterative Case

 How many times does
 it repeat?
 What controls how
 many times it repeats?
 How are you going to
 set parameter values in
 a handy way for each
 “pass”

           Intro to Technical Problem Solving with MATLAB v.7
                                                                132
  Iteration over Elements of a
  Row Vector
               Name of var that changes
mySum = 0;                          Values taken on
for itemThisTime = [1 0 -5 78]      by changing var
  mySum = mySum + itemThisTime;
  display(itemThisTime);
  display(mySum );
  disp('====')      Code to be repeated
end

disp('***********************')
mySum         Intro to Technical Problem Solving with MATLAB v.7
                                                                   133
 Iteration over Columns of an
 Array Name of var that changes
sumColumnProducts = 0;                   Values taken on
for oneCol = [1 0 -5 78; 61 9 44 10]     by changing var
    sumColumnProducts = sumColumnProducts +
   oneCol(1)*oneCol(2);
   display(oneCol);
   display(sumColumnProducts);
   disp('====')        Code to be repeated
end

disp('***********************')
sumColumnProducts
             Intro to Technical Problem Solving with MATLAB v.7
                                                                  134
Nested FOR Loops


 function cellSum = prob8_A_11(A,B)
 % Calculates cell-by-cell sum of two arrays
 % Input: 2 arrays of dimensions nxm
 % Output: Cell-by-cell product array nxm
 [nRows,nCols] = size(A);
 cellSum = zeros(nRows, nCols);
 for i=1:nRows
      for j=1:nCols
             cellSum(i,j)=A(i,j)+B(i,j);
      end
 end

                   Intro to Technical Problem Solving with MATLAB v.7
                                                                        135
Synopsis for FOR
 FOR loops are used in cases where you need more control
 over computations than allowed in cell-by-cell operations.
 FOR loops start with a code line that begins with keyword
 for and end with keyword end.
 FOR loops iterate over a code block body using successive
 values of supplied vector or array.
 If a FOR loop is supplied with an array, then successive
 values of the columns of the array are set to the value of
 the loop variable.
 To understand a FOR loop, a good strategy is to “step
 through” the loop.
             Intro to Technical Problem Solving with MATLAB v.7
                                                                  136
8-4 Conditional Program Flow
                           if <conditions>
   Form 1: IF                    <statements>
                           end;

J&T Computers is planning to give a
  $3,000 holiday bonus to every
  employee provided ALL
  employees have a performance
  evaluation higher than 3/5.
For the dataset, find if bonus will be
  given.
                                                          Employee Numbers,
                                                     Performance Ratings, Salaries
                Intro to Technical Problem Solving with MATLAB v.7
                                                                               137
Conditional Program Flow
cont’d       if <conditions>
                                           <statements>
   Form 2: IF/ELSE             else
                                           <statements>
                               end;


Instead of giving bonus to all
   employees, consider the following
   scenario:
every employee with a
performance rating of 4 or 5 gets a 5
   percent holiday bonus while all
   other employees will get a 2                          Employee Numbers,
   percent bonus.                                   Performance Ratings, Salaries
               Intro to Technical Problem Solving with MATLAB v.7
                                                                              138
Conditional Program Flow
cont’d         if <conditions>
                                           <statements>
   Form 3: IF/ELSEIF                 elseif
                                           <statements>
                                     end;


New scenario:
Employees with performance
ratings of 5 get a 4% bonus, those
   with performance ratings of 4 get
   a
2% bonus, and those with
   performance ratings of 3 get a 1%                     Employee Numbers,
   bonus.                                           Performance Ratings, Salaries
               Intro to Technical Problem Solving with MATLAB v.7
                                                                              139
Conditional Program Flow
cont’d         if <conditions>
                     <statements>
                                    elseif
                                          <statements>
   Form 4:                          else
   IF/ELSEIF/ELSE                         <statements>
                                    end;

One last scenario:
employees with performance ratings
  of 5 get a 4% bonus, those with
  performance ratings of 4 get a 3%
  bonus, those with performance
  ratings of 3 get a 2% bonus, and
  everyone else gets a 1% bonus                         Employee Numbers,
                                                   Performance Ratings, Salaries
              Intro to Technical Problem Solving with MATLAB v.7
                                                                             140
Sample Problem

  I will be depositing $5,000 in the beginning
    of every year in my bank account. The
    bank offers an interest rate of 4%.

      When will I be a millionaire?
      How much savings will I have after 10 years?


            Intro to Technical Problem Solving with MATLAB v.7
                                                                 141
Synopsis
 IF-THEN-ELSE can be used to express conditional
 program control. It is best understood in four distinct
 forms.
 1. IF: In this form, one relational/logical test exists. During
    execution, if the test results in true, then the commands in the
    following block are run. If the test results in false, then the
    commands are not run.
 2. IF-ELSE: This form performs a relational/logical test and, if true,
    then runs a set of commands. If false, an alternative set of
    commands is run.
 3. IF-ELSEIF: There can be multiple ELSEIF clauses. Only one (at
    most) code block following a test will be run, which will be the
    one following the first test that results in true.
 4. IF-ELSEIF-ELSE: This form is a combination of the second and
    third forms.
 The key to effective use is to correctly match the problem
 situation you have with one of the appropriate four forms.
              Intro to Technical Problem Solving with MATLAB v.7
                                                                     142

				
DOCUMENT INFO