an introduction to technical problem solving with matlab v.7 jon sticklen, phd m. taner eskil, phd

142
An Introduction To An Introduction To Technical Problem Solving Technical Problem Solving with MATLAB v.7 with MATLAB v.7 Jon Sticklen, PhD Jon Sticklen, PhD M. Taner Eskil, PhD M. Taner Eskil, PhD

Upload: clyde-obrien

Post on 22-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

An Introduction ToAn Introduction ToTechnical Problem Solving Technical Problem Solving with MATLAB v.7with MATLAB v.7

Jon Sticklen, PhDJon Sticklen, PhD

M. Taner Eskil, PhDM. Taner Eskil, PhD

Page 2: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

IntroductionIntroduction

Chapter 1Chapter 1

Page 3: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 3

IntroductionIntroduction

What is Technical Problem Solving?What is Technical Problem Solving?

The Path to Becoming a Good Technical The Path to Becoming a Good Technical

Problem SolverProblem Solver

What You Must Do to Master the MaterialWhat You Must Do to Master the Material

Page 4: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 4

1-1 What is Technical Problem 1-1 What is Technical Problem Solving?Solving?

Good common sense applied to technical Good common sense applied to technical problemsproblems

Quantitative in natureQuantitative in nature

Basis for making many decisionsBasis for making many decisions

Rooted in numerical calculationsRooted in numerical calculations

Decompose the problemDecompose the problem

Mainstay of what an engineer doesMainstay of what an engineer does

Page 5: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 5

1-2 The Path to Becoming a 1-2 The Path to Becoming a Good Technical Problem SolverGood Technical Problem Solver

Master the conceptual subject matter of a Master the conceptual subject matter of a given technical areagiven technical area

Demonstrate what you have learnedDemonstrate what you have learned

Master the tools of the tradeMaster the tools of the tradeMATLABMATLAB

MathematicaMathematica

MathCadMathCad

Page 6: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 6

1-3 What You Must Do to Master 1-3 What You Must Do to Master the Materialthe Material

Be prepared to spend substantial time Be prepared to spend substantial time

learning this materiallearning this material

Read assigned sections of the text with Read assigned sections of the text with

MATLAB at your sideMATLAB at your side

Work the problems hands-onWork the problems hands-on

Page 7: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

A Framework for Technical A Framework for Technical Problem SolvingProblem Solving

Chapter 2Chapter 2

Page 8: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 8

A Framework for Technical A Framework for Technical Problem SolvingProblem Solving

Steps in a Framework for Technical Steps in a Framework for Technical

Problem SolvingProblem Solving

An Example Using the FrameworkAn Example Using the Framework

Page 9: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 9

2-1 Steps in a Framework for 2-1 Steps in a Framework for Technical Problem SolvingTechnical Problem Solving

Step 1: Refine and StructureStep 1: Refine and StructureArrive at a precise problem statementArrive at a precise problem statement

Give the problem initial structure:Give the problem initial structure:Problem inputsProblem inputs

Computational outputComputational output

Step 2: Make a sketch or diagramStep 2: Make a sketch or diagramVisualize the physical situationVisualize the physical situation

Page 10: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 10

2-1 Steps in a Framework for 2-1 Steps in a Framework for Technical Problem SolvingTechnical Problem Solving

Step 3: Assemble and OrganizeStep 3: Assemble and OrganizeWhat do you need to know to solve the What do you need to know to solve the problem?problem?

Get the needed information:Get the needed information:Internet search engines such as Yahoo or GoogleInternet search engines such as Yahoo or Google

LibraryLibrary

Step 4: SimplifyStep 4: SimplifyFind if there are suitable approximationsFind if there are suitable approximations

Page 11: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 11

2-1 Steps in a Framework for 2-1 Steps in a Framework for Technical Problem SolvingTechnical Problem Solving

Step 5: DecomposeStep 5: DecomposeSimpler problemsSimpler problems

Reduce the complexity of the solutionReduce the complexity of the solution

Step 6: Dimensional AnalysisStep 6: Dimensional AnalysisAre the mathematical relationships you intend Are the mathematical relationships you intend to apply in your solution flawed?to apply in your solution flawed?

Substitute the units for each variable and Substitute the units for each variable and algebraically simplifyalgebraically simplify

Page 12: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 12

2-1 Steps in a Framework for 2-1 Steps in a Framework for Technical Problem SolvingTechnical Problem Solving

Step 7: Compute and DiscussStep 7: Compute and DiscussPerform the computations needed to obtain a Perform the computations needed to obtain a solutionsolution

Use a computational tool such as MATLABUse a computational tool such as MATLAB

Examine and understand the resultsExamine and understand the resultsBe ready to explain them!Be ready to explain them!

Page 13: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 13

2-2 An Example Using the 2-2 An Example Using the FrameworkFramework

Problem:Problem:What is the optimum firing angle we should set What is the optimum firing angle we should set for a catapult whose purpose is to hurl hay for a catapult whose purpose is to hurl hay bales to a herd of starving caribou, given the bales to a herd of starving caribou, given the initial velocity of hay bales as they exit the initial velocity of hay bales as they exit the catapult?catapult?

Page 14: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 14

2-2.1 Refine and Structure2-2.1 Refine and Structure

Clarify:Clarify:Think about the problemThink about the problemThe ultimate source of information is the person setting The ultimate source of information is the person setting the problemthe problem

Refine:Refine:What is the firing angle of a catapult in order to hurl What is the firing angle of a catapult in order to hurl projectilesprojectiles a maximum horizontal distancea maximum horizontal distance given the given the initial velocity of the initial velocity of the objectobject??

What are the Input(s) and Output(s)?What are the Input(s) and Output(s)?Initial speed, angle, maximized distanceInitial speed, angle, maximized distance

Page 15: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 15

2-2.2 Sketch or Diagram2-2.2 Sketch or Diagram

What is the firing angle measured What is the firing angle measured from the from the horizontalhorizontal we should set for a catapult to hurl we should set for a catapult to hurl projectiles a maximum horizontal distance given projectiles a maximum horizontal distance given the initial velocity of the object?the initial velocity of the object?

h

D

L1

L2

g

s

Page 16: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 16

2-2.3 Background Knowledge2-2.3 Background Knowledge

For our example:For our example:General knowledge of physicsGeneral knowledge of physics

General knowledge of one way in which General knowledge of one way in which optimizing problems may be solvedoptimizing problems may be solved

Seek the value of the firing angle Seek the value of the firing angle that that maximizes the total horizontal distance maximizes the total horizontal distance DD traveled given an initial speed of the hay traveled given an initial speed of the hay bale as it comes out of the catapultbale as it comes out of the catapult

Page 17: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 17

2-2.4 Assumptions and 2-2.4 Assumptions and ApproximationsApproximations

Many times in technical problem solving, the path Many times in technical problem solving, the path to a solution leads to making assumptions about to a solution leads to making assumptions about the problem and then solving the simplified the problem and then solving the simplified version of the problem.version of the problem.

Negligible air resistanceNegligible air resistanceNo difference between a hay bale and a snowballNo difference between a hay bale and a snowball

Be aware of the assumptions you are making and Be aware of the assumptions you are making and communicate them to the person who originally communicate them to the person who originally set the problem for you.set the problem for you.

Importance of good documentationImportance of good documentation

Page 18: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 18

2-2.5 Decomposing /Recursive 2-2.5 Decomposing /Recursive StructuringStructuring

Break the problem into pieces, each with its Break the problem into pieces, each with its

own well defined input and outputown well defined input and output

Develop technical solutions for each pieceDevelop technical solutions for each piece

Work backwards to find what you needWork backwards to find what you need

Page 19: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 19

2-2.6 Dimensional Analysis2-2.6 Dimensional Analysis

g

sD o )cos()sin(2 2

2

2

sftsft

ft

ftft

Page 20: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 20

2-2.7 Putting It All Together2-2.7 Putting It All Together

2max 031.0 osD

(degrees)(degrees) 00 1010 2020 3030 4040

Unit Distance (feet)Unit Distance (feet) 0.00000.0000 0.01070.0107 0.02010.0201 0.02710.0271 0.03080.0308

(degrees)(degrees) 9090 8080 7070 6060 5050

Unit Distance (feet)Unit Distance (feet) 0.00000.0000 0.01070.0107 0.02010.0201 0.02710.0271 0.03080.0308

Page 21: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 21

2-2 Synopsis2-2 Synopsis

Identify input and output variables correctlyIdentify input and output variables correctly

Create a sketch of the physical situationCreate a sketch of the physical situation

Generalize the problemGeneralize the problem

Apply general background knowledgeApply general background knowledge

General approach to optimization problemsGeneral approach to optimization problems

Page 22: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

MATLAB Basics: ScalarsMATLAB Basics: Scalars

Chapter 3Chapter 3

Page 23: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 23

ScalarsScalars

The First Time You Bring Up MATLABThe First Time You Bring Up MATLAB

MATLAB as a Calculator for ScalarsMATLAB as a Calculator for Scalars

Fetching and Setting Scalar VariablesFetching and Setting Scalar Variables

MATLAB Built-in Functions, Operators, MATLAB Built-in Functions, Operators, and Expressionsand Expressions

Problem Sets for ScalarsProblem Sets for Scalars

Page 24: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 24

3-1 The First Time You Bring 3-1 The First Time You Bring Up MATLABUp MATLABBasic windows in MATLAB are:Basic windows in MATLAB are:

Command - executes single-line commandsCommand - executes single-line commandsWorkspace - keeps track of all defined variablesWorkspace - keeps track of all defined variablesCommand History - keeps a running record of all single Command History - keeps a running record of all single line programs you have executedline programs you have executedCurrent Folder - lists all files that are directly available for Current Folder - lists all files that are directly available for MATLAB useMATLAB useArray Editor - allows direct editing of MATLAB arraysArray Editor - allows direct editing of MATLAB arraysPreferences - for setting preferences for the display of Preferences - for setting preferences for the display of results, fonts used, and many other aspects of how results, fonts used, and many other aspects of how MATLAB looks to youMATLAB looks to you

Page 25: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 25

3-2 MATLAB as a Calculator for 3-2 MATLAB as a Calculator for ScalarsScalars

A scalar is simply a number…A scalar is simply a number…

In science the term scalar is used as opposed to a vector, In science the term scalar is used as opposed to a vector, i.e. i.e. a magnitude having no directiona magnitude having no direction..

In MATLAB, scalar is used as opposed to arrays, i.e. In MATLAB, scalar is used as opposed to arrays, i.e. a a single numbersingle number. .

Since we have not covered arrays (tables of numbers) Since we have not covered arrays (tables of numbers) yet, we will be dealing with scalars in MATLAB.yet, we will be dealing with scalars in MATLAB.

,4,7

22,5.3

Page 26: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 26

Using the Command History Using the Command History WindowWindow

Page 27: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 27

3-3 Fetching and Setting Scalar 3-3 Fetching and Setting Scalar VariablesVariables

Think of computer Think of computer variables as variables as named named containerscontainers. .

We can perform 2 We can perform 2 types of operations types of operations on variables:on variables:

we can set the value held in the container: x = 22we can set the value held in the container: x = 22

we can look at the value held in the container: xwe can look at the value held in the container: x

Page 28: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 28

The Assignment Operator (=)The Assignment Operator (=)

The equal sign is the assignment operator in The equal sign is the assignment operator in MATLAB.MATLAB.

>> x = 22>> x = 22places number 22 in container xplaces number 22 in container xHow about:How about:

>> x = x + 1>> x = x + 1Note the difference between the equal sign in Note the difference between the equal sign in mathematics and the assignment operator in mathematics and the assignment operator in MATLAB!MATLAB!

Page 29: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 29

3-3.2 An Example - Setting 3-3.2 An Example - Setting Variables for the Hay Bale ProblemVariables for the Hay Bale Problem

clear deletes variables from workspace, you clear deletes variables from workspace, you should use it before starting new workshould use it before starting new work

The percent symbol is used for putting reminders The percent symbol is used for putting reminders (comments) for ourselves, ignored by MATLAB(comments) for ourselves, ignored by MATLAB

Command lines ending with semicolon do not Command lines ending with semicolon do not display the results. display the results.

>> clear>> accelGravity = 32; % units: ft/sec/sec>> speedInitial = 50; % units: ft/sec>> phi = 10; % units: degrees

Page 30: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 30

3-4 MATLAB Built-in Functions, 3-4 MATLAB Built-in Functions, Operators, and ExpressionsOperators, and Expressions

MATLAB comes with a large number of built-MATLAB comes with a large number of built-in functions (e.g.. sin, cos, tan, log10, log, exp)in functions (e.g.. sin, cos, tan, log10, log, exp)

A special subclass of often-used MATLAB A special subclass of often-used MATLAB functions is called operatorsfunctions is called operators

Assignment operator (=)Assignment operator (=)

Arithmetic operators (+, -, *, /, ^)Arithmetic operators (+, -, *, /, ^)

Relational operators (<, <=, = =, ~=, >=, >)Relational operators (<, <=, = =, ~=, >=, >)

Logical operators (&, |, ~)Logical operators (&, |, ~)

Page 31: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 31

Example – Arithmetic OperatorsExample – Arithmetic Operators

Page 32: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 32

Example – Relational and Example – Relational and Logical OperatorsLogical Operators

Page 33: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 33

3-4.2 Rules for Forming 3-4.2 Rules for Forming ExpressionsExpressions

MATLAB expressions consist of:MATLAB expressions consist of:Numerical values or variablesNumerical values or variables

Logical values or variablesLogical values or variables

Legal applications of MATLAB functions or Legal applications of MATLAB functions or operatorsoperators

A combination of MATLAB expressionsA combination of MATLAB expressions

What is the error in the following MATLAB What is the error in the following MATLAB expression?expression?

>> sin(pi/2, pi/8)>> sin(pi/2, pi/8)

Page 34: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 34

Order of PrecedenceOrder of Precedence

If two operators are at If two operators are at the same level of the same level of precedence, the precedence, the evaluation is carried out evaluation is carried out from left to rightfrom left to right

An Example – ComputeAn Example – Compute

for x = 4, y = 2for x = 4, y = 2

Page 35: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 35

Applying Scalar Computations to Applying Scalar Computations to a Problema Problem

Page 36: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 36

Synopsis for Chapter 3Synopsis for Chapter 3A MATLAB variable can be thought of as a named container. The value of a A MATLAB variable can be thought of as a named container. The value of a MATLAB variable then is the contents of the box.MATLAB variable then is the contents of the box.

Setting the variable value is done using the assignment operator; fetching the 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.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.In MATLAB the type of a variable is defined by the way the variable is used.

Scalars are simple numbers.Scalars are simple numbers.

Logical values can be TRUE (any non-zero number) or FALSE (0).Logical values can be TRUE (any non-zero number) or FALSE (0).

MATLAB operators are a special subclass of MATLAB built-in functions.MATLAB operators are a special subclass of MATLAB built-in functions.

Arithmetic operators take numerical variables as input and output a numerical Arithmetic operators take numerical variables as input and output a numerical result.result.

Relational operators take numerical variables as input and output a logical Relational operators take numerical variables as input and output a logical result.result.

Logical operators take logical 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.MATLAB expressions are blueprints for performing computations.

Page 37: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Saving MATLAB WorkSaving MATLAB Work

Chapter 4Chapter 4

Page 38: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 38

Saving MATLAB WorkSaving MATLAB Work

The MATLAB “Current Directory”The MATLAB “Current Directory”

Saving MATLAB Commands in Script FilesSaving MATLAB Commands in Script Files

Saving MATLAB Commands in User-Saving MATLAB Commands in User-Defined Function FilesDefined Function Files

Testing and Debugging MATLAB Script and Testing and Debugging MATLAB Script and Function FilesFunction Files

Problem Sets for “Saving Your Work”Problem Sets for “Saving Your Work”

Page 39: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 39

4-1 The MATLAB Current 4-1 The MATLAB Current DirectoryDirectory

It is the default folder MATLAB will save filesIt is the default folder MATLAB will save files

It is the first folder MATLAB will attempt to load filesIt is the first folder MATLAB will attempt to load files

It may be changed interactively using the Current It may be changed interactively using the Current Directory Window or built-in commandsDirectory Window or built-in commands

MATLAB starts MATLAB starts up with the up with the default folder default folder connectedconnected

Page 40: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 40

4-2 Saving MATLAB Commands 4-2 Saving MATLAB Commands in Script Filesin Script Files

Script files are lines of code just like you Script files are lines of code just like you would type in to the Command Windowwould type in to the Command Window

It is good programming practice to include It is good programming practice to include comments for:comments for:

The location of the fileThe location of the file

Variables used in the script but defined outsideVariables used in the script but defined outside

Results produced by the scriptResults produced by the script

Units of values calculated in the scriptUnits of values calculated in the script

Page 41: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 41

An Example – The Water Tower An Example – The Water Tower ProblemProblem

compute water tower cost compute water tower cost and volumeand volume

cylinder caped by cylinder caped by hemispherehemisphere

diameter and height of diameter and height of cylinder knowncylinder known

known cost/mknown cost/m22 for for hemisphere and for hemisphere and for cylindercylinder

Page 42: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 42

Synopsis for MATLAB ScriptsSynopsis for MATLAB ScriptsA script file consists of groups of MATLAB A script file consists of groups of MATLAB commands bundled together into a modulecommands bundled together into a module

Scripts files have a DOT-M extensionScripts files have a DOT-M extension

When executing inside a script file, all variables When executing inside a script file, all variables in the workspace are availablein the workspace are available

Variables created in a script are available at the Variables created in a script are available at the Command Window and in other scriptsCommand Window and in other scripts

Making a sketch of a problem is important in Making a sketch of a problem is important in making the problem context concretemaking the problem context concrete

Page 43: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 43

4-3 Saving MATLAB Commands 4-3 Saving MATLAB Commands in User-Defined Function Filesin User-Defined Function Files

Scripts - these are lines of code exactly like Scripts - these are lines of code exactly like you could type in to the command windowyou could type in to the command window

Functions - are “computational boxes.” You Functions - are “computational boxes.” You give them a set of input values, and they give them a set of input values, and they calculate a set of output values. Purpose of calculate a set of output values. Purpose of functions is the same as the purpose of scripts functions is the same as the purpose of scripts + +

modularize your codemodularize your code

Page 44: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 44

Central Points…Central Points…The only way of getting a variable’s value into a The only way of getting a variable’s value into a function is for that variable to be input to the function. function is for that variable to be input to the function.

The only way of getting a value out of a function is for The only way of getting a value out of a function is for that variable to be output from the function. that variable to be output from the function.

A variable used inside a function that is not an input or A variable used inside a function that is not an input or an output variable is not visible outside the function. an output variable is not visible outside the function.

An example:An example:

>> x = pi;>> x = pi;

>> y = sin(x)>> y = sin(x)

Page 45: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 45

Syntax of a User Defined FunctionSyntax of a User Defined Function

Functions are saved in DOT M files - just Functions are saved in DOT M files - just like the script fileslike the script files

Same rules for the connected directory Same rules for the connected directory appliesapplies

First line of the file defines First line of the file defines Name of the functionName of the function

Input variable(s)Input variable(s)

Output variable(s)Output variable(s)

Page 46: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 46

Defining a function – the first lineDefining a function – the first linefunction <outputVars> = <function name>(<inputVars>)

Keyword - has to be exactly as appears

0, 1, or more vars. If more than 1, put in square brackets.

You choose the name - see text or ML help for valid name - mostly just start with a regular character and have no spaces.

0, 1, or more vars. If 0, then the enclosing parens are not needed.

required

Page 47: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 47

Linkage Between Actual and Linkage Between Actual and Formal ParametersFormal Parameters

...

z = myFun3(a,b)

...

calling program:

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.

Page 48: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 48

Comments in FunctionsComments in Functions

There are no uniformly agreed upon rules for There are no uniformly agreed upon rules for inserting comments into functions inserting comments into functions

It is always good programming practice to include It is always good programming practice to include comment lines indicating:comment lines indicating:

the purpose of the functionthe purpose of the function

the inputs to the functionthe inputs to the function

the outputs from the functionthe outputs from the function

any assumptionsany assumptions

Page 49: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 49

ExamplesExamplesfunction <outputVars> = <function name>(<inputVars>)

For each of the following function definitions, For each of the following function definitions, how many input and output variables are how many input and output variables are there?there?

function x = myFun1function x = myFun1

function z = myFun2(y)function z = myFun2(y)

function out33 = myFun3(x,y)function out33 = myFun3(x,y)

function [a,b] = myFun4(q,r)function [a,b] = myFun4(q,r)

Page 50: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 50

ExamplesExamples

Page 51: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 51

ExamplesExamples

Page 52: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 52

Synopsis for User-Defined Synopsis for User-Defined FunctionsFunctions

The workspace of a function is insulated from the outside.The workspace of a function is insulated from the outside.

When a MATLAB function is called, a linkage is made When a MATLAB function is called, a linkage is made between the actual parameters in the call and the formal between the actual parameters in the call and the formal parameters in the function definition.parameters in the function definition.

The number of actual input parameters must be the same The number of actual input parameters must be the same as the number of formal input parameters. This is also as the number of formal input parameters. This is also valid for the output parameters.valid for the output parameters.

The first line of a MATLAB function begins with the The first line of a MATLAB function begins with the keyword keyword functionfunction, and the rest of the first line looks like an , and the rest of the first line looks like an assignment statement.assignment statement.

Page 53: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 53

4-4 Testing and Debugging 4-4 Testing and Debugging MATLAB Script and Function FilesMATLAB Script and Function Files

Types of errors in programs:Types of errors in programs:

Syntax errorsSyntax errorsResults from incorrect application of MATLAB rulesResults from incorrect application of MATLAB rules

MATLAB aborts the computation and points of the error MATLAB aborts the computation and points of the error

Runtime errorsRuntime errorsResults from incorrect logic and MATLAB not doing Results from incorrect logic and MATLAB not doing what you intendwhat you intend

For this type error MATLAB debugging facilities are For this type error MATLAB debugging facilities are usefuluseful

Page 54: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 54

ExamplesExamples

Page 55: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 55

ExamplesExamples

Page 56: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 56

Synopsis for DebuggingSynopsis for Debugging

Identify the set of inputs you will use for the testIdentify the set of inputs you will use for the test

Determine what you expect for each of the test Determine what you expect for each of the test input sets to produce input sets to produce

Compare what you expect to what MATLAB Compare what you expect to what MATLAB produces to identify runtime errors in the functionproduces to identify runtime errors in the function

Identify and correct the line(s) of code that are Identify and correct the line(s) of code that are causing the runtime errorcausing the runtime error

Page 57: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Vector OperationsVector Operations

Chapter 5Chapter 5

Page 58: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 58

Vector OperationsVector Operations

Vector CreationVector Creation

Accessing Vector ElementsAccessing Vector Elements

Row Vectors and Column Vectors, and the Row Vectors and Column Vectors, and the Transpose OperatorTranspose Operator

Vector Built-in Functions, Operators, and Vector Built-in Functions, Operators, and ExpressionsExpressions

Page 59: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 59

5-1 Vector Creation5-1 Vector CreationVectors are defined in square brackets;Vectors are defined in square brackets;

temperaturesMonThu = [32 31 29 33];temperaturesMonThu = [32 31 29 33];temperaturesFriSat = [35 33];temperaturesFriSat = [35 33];

You can concatenate a vector with a scalar;You can concatenate a vector with a scalar;temperaturesFriSun = [35 33 27];temperaturesFriSun = [35 33 27];

or concatenate 2 vectors;or concatenate 2 vectors;weeklyTemperatures = [temperaturesMonThu, temperaturesFriSun];weeklyTemperatures = [temperaturesMonThu, temperaturesFriSun];

To find the size of a vector, we use length; To find the size of a vector, we use length; numTemperatures = length(weeklyTemperatures);numTemperatures = length(weeklyTemperatures);

We could find the average temperature by typing;We could find the average temperature by typing;avgTemperature = mean(dailyTemperatures)avgTemperature = mean(dailyTemperatures)

or by using sum and length; or by using sum and length; totalTemperature = sum(dailyTemperatures)/length(dailyTemperatures);totalTemperature = sum(dailyTemperatures)/length(dailyTemperatures);

Page 60: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 60

Some Useful Vector FunctionsSome Useful Vector Functions

brackets (e.g. [27 36 41]): Creates vectors.brackets (e.g. [27 36 41]): Creates vectors.

colon operator (e.g. [0:5:30]): Creates linearly spaced vectors.colon operator (e.g. [0:5:30]): Creates linearly spaced vectors.

linspacelinspace (e.g. linspace(0,100,21)): Creates linearly spaced vectors. (e.g. linspace(0,100,21)): Creates linearly spaced vectors.

length length (e.g. length([0:5:30])): Finds the length of a vector.(e.g. length([0:5:30])): Finds the length of a vector.

zeroszeros (e.g. zeros(1,5)): Creates vectors filled with zeroes. (e.g. zeros(1,5)): Creates vectors filled with zeroes.

onesones (e.g. ones(1,5): Creates vectors filled with ones. (e.g. ones(1,5): Creates vectors filled with ones.

sumsum (e.g. sum([5 3 6 2])): Sums up the contents of a vector. (e.g. sum([5 3 6 2])): Sums up the contents of a vector.

sortsort (e.g. sort([5 3 6 2])): Sorts the contents of a vector. (e.g. sort([5 3 6 2])): Sorts the contents of a vector.

meanmean (e.g. mean([5 3 6 2])): Finds the average of contents. (e.g. mean([5 3 6 2])): Finds the average of contents.

Page 61: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 61

5.2 – Accessing Vector Elements – 5.2 – Accessing Vector Elements – ExamplesExamples

1.1. Create a row vector x consisting of the numbers in Create a row vector x consisting of the numbers in the ordered set: {1 4 7 10} using the colon the ordered set: {1 4 7 10} using the colon operator. operator.

x = [1:3:10]x = [1:3:10]

2.2. Set a variable y to be the length of x. Set a variable y to be the length of x.

y = length(x)y = length(x)

3.3. Set variable y to be the 1st element of x. Set variable y to be the 1st element of x.

y = x(1)y = x(1)

4.4. Set variable y to be the 1st, 2nd, and 3rd elements Set variable y to be the 1st, 2nd, and 3rd elements of x. of x.

y = x([1,2,3]) OR y = x(1:3)y = x([1,2,3]) OR y = x(1:3)

Page 62: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 62

Accessing Vector Elements – Accessing Vector Elements – Example cont’d.Example cont’d.

5.5. Set variable y to be the 3rd through the last element of x - Set variable y to be the 3rd through the last element of x - and do so such that your solution works no matter how and do so such that your solution works no matter how long x is. long x is.

y = x(3:end)y = x(3:end)

6.6. Set variable y to be the next-to-last and last element of x - 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 and do so such that your solution works no matter how long x is. long x is.

y = x([end-1,end])y = x([end-1,end])

7.7. Change the 2nd element of x to be 3. Change the 2nd element of x to be 3.

x(2) = 3x(2) = 3

8.8. Change the 2nd element of x to be 102 and the 4th element Change the 2nd element of x to be 102 and the 4th element of x be 205. of x be 205.

x([2,4]) = [102, 205]x([2,4]) = [102, 205]

Page 63: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 63

Synopsis for Fetching and Setting Synopsis for Fetching and Setting Elements in VectorsElements in Vectors

Access to whole vector is similar to scalar access.Access to whole vector is similar to scalar access.Accessing element(s) in a vector is done by indexing into Accessing element(s) in a vector is done by indexing into the vector.the vector.To delete element(s) in a vector, empty square brackets are To delete element(s) in a vector, empty square brackets are used.used.To find the length of a vector V, use the length built-in To find the length of a vector V, use the length built-in function length(V).function length(V).When setting elements of a vector, the number of elements When setting elements of a vector, the number of elements being set must be equal to the number of elements in the being set must be equal to the number of elements in the vector on the right hand side of the assignment operation. vector on the right hand side of the assignment operation. The exception is that a scalar on the right-hand side can be The exception is that a scalar on the right-hand side can be used to set multiple vector elements.used to set multiple vector elements.

Page 64: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 64

5-3 Row Vectors and Column 5-3 Row Vectors and Column Vectors, and the Transpose OperatorVectors, and the Transpose Operator

Row and column vectors are represented as single Row and column vectors are represented as single rows and columns of values, respectively.rows and columns of values, respectively.When creating a column vector with square When creating a column vector with square brackets, you may use the semicolon operator:brackets, you may use the semicolon operator:

temp = [35; 33; 27];temp = [35; 33; 27];

or you may use the transpose operator;or you may use the transpose operator;temp = [35 33 27]’;temp = [35 33 27]’;

When creating an equally spaced column vector, When creating an equally spaced column vector, you need to use the transpose operator; you need to use the transpose operator;

springConstants = [10:10:100]’;springConstants = [10:10:100]’;springConstants = linspace(10,100,10)’;springConstants = linspace(10,100,10)’;

Page 65: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 65

5-4 Vector Built-in Functions, 5-4 Vector Built-in Functions, Operators, and ExpressionsOperators, and Expressions

Page 66: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 66

Sample Problem – Vector Built-Sample Problem – Vector Built-in Functionsin Functions

Page 67: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 67

Sample Problem – Vector Sample Problem – Vector Arithmetic OperatorsArithmetic Operators

Page 68: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 68

Sample Problem – Vector Sample Problem – Vector Arithmetic OperatorsArithmetic Operators

Page 69: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 69

Sample Problem – Vector Sample Problem – Vector Arithmetic OperatorsArithmetic Operators

Page 70: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 70

Vector Relational OperatorsVector Relational Operators

Think of them as comparing numbers…Think of them as comparing numbers…

<, >, = =, >=, <=<, >, = =, >=, <=

A relational operator can be used to A relational operator can be used to compare the values of two variablescompare the values of two variables

a>ba>b

But… remember MATLAB is for matricesBut… remember MATLAB is for matrices

what are you testing?what are you testing?

Page 71: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 71

What are you testing?What are you testing?

Number (scalar) vs. NumberNumber (scalar) vs. Number

Number vs. Vector (or Matrix)Number vs. Vector (or Matrix)A scalar is compared to each element of the vector… A scalar is compared to each element of the vector…

5<[1:10]5<[1:10]

Vector vs. VectorVector vs. VectorEach corresponding element of the two vectors is Each corresponding element of the two vectors is compared… compared…

[1:10]<=[10:-1:1][1:10]<=[10:-1:1]

Page 72: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 72

Sample Problem – Vector Sample Problem – Vector Relational OperatorsRelational Operators

Page 73: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 73

Vector Logical OperatorsVector Logical Operators

They operate on the They operate on the resultsresults of relational operators of relational operators How many elements in vector x are in range How many elements in vector x are in range (6,10)?(6,10)?How many elements in x areHow many elements in x are

… … greater than 6greater than 6ANDAND… … less than 10?less than 10?

We use logical operators…We use logical operators…AND (&), OR (|), NOT (~)AND (&), OR (|), NOT (~)any, allany, all

Page 74: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 74

Sample Problem – Vector Sample Problem – Vector Logical OperatorsLogical Operators

Page 75: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 75

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

Page 76: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

2-D Plotting and Help in 2-D Plotting and Help in MATLABMATLAB

Chapter 6Chapter 6

Page 77: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 77

2-D Plotting and Help in 2-D Plotting and Help in MATLABMATLAB

Using EZPLOT to Plot FunctionsUsing EZPLOT to Plot Functions

Using Vectors to Plot Numerical DataUsing Vectors to Plot Numerical Data

Overlay plots and subplotsOverlay plots and subplots

Other 2-D plot types in MATLABOther 2-D plot types in MATLAB

Problem Sets for 2-D PlottingProblem Sets for 2-D Plotting

Page 78: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 78

6-1 Using EZPLOT to Plot 6-1 Using EZPLOT to Plot FunctionsFunctions

Page 79: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 79

Getting HelpGetting Help

You can’t possibly learn everything there is You can’t possibly learn everything there is to know about MATLAB,to know about MATLAB,

… … and you don’t need to.and you don’t need to.

It is crucial to develop the ability to It is crucial to develop the ability to augment your knowledge in MATLAB augment your knowledge in MATLAB toward accomplishing a given task.toward accomplishing a given task.

Page 80: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 80

Getting Help cont’dGetting Help cont’d

Page 81: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 81

Getting Help cont’dGetting Help cont’d

Click the tab in the navigation pane labeled Click the tab in the navigation pane labeled SearchSearch. .

Then type into the Search field the name Then type into the Search field the name ezplotezplot..

Page 82: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 82

Using EZPLOT to Plot FunctionsUsing EZPLOT to Plot Functions

There are three forms of There are three forms of ezplotezplot::

f(x) f(x) e.g., f(t) = 3ee.g., f(t) = 3e-2t-2tcos(5t)cos(5t)

ezplot('3*exp(-2*t)*cos(5*t)')ezplot('3*exp(-2*t)*cos(5*t)')

f(t), g(t) f(t), g(t) e.g., f(t) = 3te.g., f(t) = 3t22 + 2; g(t) = sin(5t) + 2; g(t) = sin(5t)

ezplot('3*t^2 + 2', 'sin(5*t)')ezplot('3*t^2 + 2', 'sin(5*t)')

f(x,y) = 0 f(x,y) = 0 e.g., f(x,y) = 3xy + ye.g., f(x,y) = 3xy + y2 2 + 55 = 0+ 55 = 0

ezplot('3*x*y + y^2 + 55',[-30,30,-ezplot('3*x*y + y^2 + 55',[-30,30,-

20,20])20,20])

Page 83: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 83

Sample Problem - EZPLOTSample Problem - EZPLOT

Page 84: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 84

Graphing with MATLABGraphing with MATLABUse Use ezplotezplot to make a quick and dirty chart of to make a quick and dirty chart of functions. functions. Optional arguments allow changing the default Optional arguments allow changing the default functional domain [-2π, 2π].functional domain [-2π, 2π].Use Use xlabelxlabel, , ylabelylabel, and , and titletitle built-in functions to built-in functions to refine labeling the plots made by refine labeling the plots made by ezplotezplot. . When needed, use When needed, use grid grid to activate a grid on a plot to activate a grid on a plot created. created. If you would like to keep the existing graph and If you would like to keep the existing graph and generate a new one, use generate a new one, use figurefigure..

Page 85: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 85

6-2 Using Vectors to Plot 6-2 Using Vectors to Plot Numerical DataNumerical Data

Mostly from observed data - your goal is to understand the Mostly from observed data - your goal is to understand the relationship between the variables of a system.relationship between the variables of a system.

Determine the independent and dependent variables and plot:Determine the independent and dependent variables and plot:speed = 20:10:70;speed = 20:10:70;stopDis = [46,75,128,201,292,385];stopDis = [46,75,128,201,292,385];plot(speed, stopDis, '-ro') plot(speed, stopDis, '-ro') % note the ‘-ro’ switch% note the ‘-ro’ switch

Don’t forget to properly label your graphs:Don’t forget to properly label your graphs:title('Stopping Distance versus Vehicle Speed', 'FontSize', 14)title('Stopping Distance versus Vehicle Speed', 'FontSize', 14)xlabel('vehicle speed (mi/hr)', 'FontSize', 12)xlabel('vehicle speed (mi/hr)', 'FontSize', 12)ylabel('stopping distance (ft)', 'FontSize', 12)ylabel('stopping distance (ft)', 'FontSize', 12)grid ongrid on

Speed (mi/hr)Speed (mi/hr) 2020 3030 4040 5050 6060 7070

Stopping Distance (ft)Stopping Distance (ft) 4646 7575 128128 201201 292292 385385

Page 86: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 86

Sample Problem – Plotting Sample Problem – Plotting Numerical DataNumerical Data

Page 87: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 87

Plotting Functions NumericallyPlotting Functions Numerically

ezplotezplot is a great tool for plotting functions, but it has several is a great tool for plotting functions, but it has several disadvantages:disadvantages:

it doesn’t provide as much control as it doesn’t provide as much control as plotplot, e.g. dotted lines., e.g. dotted lines.you must fill in values for any constants, e.g. you must fill in values for any constants, e.g.

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

hd

Vcylinder 4

2

Page 88: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 88

Sample Problem – Plotting Sample Problem – Plotting Functions NumericallyFunctions Numerically

A function G(x,y,z) of three independent variables A function G(x,y,z) of three independent variables is defined as:is defined as:

Write a function that takes no inputs or outputs but Write a function that takes no inputs or outputs but creates a plot of G(x,y,z), subject to:creates a plot of G(x,y,z), subject to:

0.1 < x < 40.1 < x < 4

y = 5, z = 3y = 5, z = 3

Page 89: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 89

Synopsis for Synopsis for ezplot ezplot and and plotplotThe first argument to plot should be the vector of values The first argument to plot should be the vector of values for the independent variable (going on the x-axis); the for the independent variable (going on the x-axis); the second argument should be the vector of values for the second argument should be the vector of values for the dependent variable (going on the y-axis).dependent variable (going on the y-axis).

An optional third argument plot is the line spec which An optional third argument plot is the line spec which specifies the type of line used (solid, dotted, etc.), the specifies the type of line used (solid, dotted, etc.), the color of the line used, and the type of data marker (if any).color of the line used, and the type of data marker (if any).

For plotting numerical data from experimentation or For plotting numerical data from experimentation or observation, use data markers.observation, use data markers.

For plotting numerical data that are computed from a For plotting numerical data that are computed from a mathematical relationship, data markers must not be used.mathematical relationship, data markers must not be used.

Page 90: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 90

6-3 Overlay Plots and Subplots6-3 Overlay Plots and Subplots

Allows putting more than one Allows putting more than one relationship directly into the same relationship directly into the same plotting window.plotting window.Two key functions: Two key functions: holdhold and and legendlegend

For multiple dependent variables For multiple dependent variables whose data are not of the same type, whose data are not of the same type, e.g. acceleration, speed and distancee.g. acceleration, speed and distanceKey function to learn: Key function to learn: subplotsubplot

Page 91: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 91

Sample Problems – Overlay Plots Sample Problems – Overlay Plots and Subplotsand Subplots

Page 92: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 92

Sample Problems – Overlay Plots Sample Problems – Overlay Plots and Subplotsand Subplots

Page 93: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 93

Synopsis for Overlay Plots and Synopsis for Overlay Plots and SubplotsSubplots

Overlay plots are used to show a family of parameterized Overlay plots are used to show a family of parameterized results results

hold onhold on is the key MATLAB command needed to turn on is the key MATLAB command needed to turn on overlaysoverlays

Subplots are used to display plots of different independent Subplots are used to display plots of different independent variables usually from one experimental data set or from variables usually from one experimental data set or from one set of equations for a single physical system.one set of equations for a single physical system.

subplotsubplot is the key MATLAB command needed to identify is the key MATLAB command needed to identify the target for a created plot.the target for a created plot.

Page 94: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

ArraysArrays

Chapter 7Chapter 7

Page 95: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 95

So far we have learned…So far we have learned…

Using MATLAB for scalar computations (Ch. 3)Using MATLAB for scalar computations (Ch. 3)

Saving your work in MATLAB user-defined Saving your work in MATLAB user-defined functions (Ch. 4)functions (Ch. 4)

Debugging MATLAB functions (Ch. 4)Debugging MATLAB functions (Ch. 4)

Using MATLAB for vector operations (Ch. 5)Using MATLAB for vector operations (Ch. 5)

Using MATLAB to make 2-D plots (Ch. 6)Using MATLAB to make 2-D plots (Ch. 6)

Using the MATLAB Help facility to let you Using the MATLAB Help facility to let you extend what you know (Ch. 6)extend what you know (Ch. 6)

Page 96: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 96

The Pattern…The Pattern…

ScalarsScalars – numbers – numbers

MatLab VectorsMatLab Vectors – Ordered, linear – Ordered, linear groupings of scalars groupings of scalars

Simple extension – MatLab ArraysSimple extension – MatLab ArraysInstead of having a one-dimensional grouping Instead of having a one-dimensional grouping of scalars as in vectors, MATLAB arrays are of scalars as in vectors, MATLAB arrays are two-dimensional groups of scalars.two-dimensional groups of scalars.

Page 97: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 97

7-1 Array Creation7-1 Array Creation

Page 98: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 98

Creating ArraysCreating Arrays

A semicolon as punctuation in the square bracket A semicolon as punctuation in the square bracket operator tells MATLAB to start a new rowoperator tells MATLAB to start a new row>> A = [1, 2, 3; 10, 20, 30]>> A = [1, 2, 3; 10, 20, 30]

linspace and the colon operator can be used to linspace and the colon operator can be used to create vectors that are subsequently composed into create vectors that are subsequently composed into an array:an array:>> A = [1:3:15; linspace(0,1,5)]>> A = [1:3:15; linspace(0,1,5)]

or…or…>> A = [(1:3:15)', linspace(0,1,5)']>> A = [(1:3:15)', linspace(0,1,5)']

Page 99: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 99

Things to know…Things to know…

A typical mistake – trying to concatenate incompatible A typical mistake – trying to concatenate incompatible vectors:vectors:>> B1 = [1, 2, 3];>> B1 = [1, 2, 3];>> B2 = [10, 11];>> B2 = [10, 11];>> stackedUpDown = [B1; B2]>> stackedUpDown = [B1; B2]??? Error using ==> vertcat??? Error using ==> vertcatAll rows in the bracketed expression must haveAll rows in the bracketed expression must havethe same number of columns.the same number of columns.

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

Page 100: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 100

Synopsis for Creating ArraysSynopsis for Creating Arrays

Semicolon punctuation inside the square bracket operator Semicolon punctuation inside the square bracket operator indicates to MATLAB that a new row is to be created.indicates to MATLAB that a new row is to be created.

When concatenating arrays, their dimensions must be When concatenating arrays, their dimensions must be consistent.consistent.

ones ones and and zeros zeros are built-in functions that create arrays are built-in functions that create arrays whose elements are all value 1 or all value 0, respectively.whose elements are all value 1 or all value 0, respectively.

ones ones and and zeros zeros take two arguments: the number of rows take two arguments: the number of rows and the number of columns in the array that will be and the number of columns in the array that will be created.created.

Page 101: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 101

7-2 Accessing Array Elements7-2 Accessing Array Elements

Page 102: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 102

Fetching ElementsFetching ElementsCreate an array A by the following:Create an array A by the following:>> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]>> 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:Pull out the value of the element at the second row, third column:>> x = A(2,3)>> x = A(2,3)

Fetch the second and third elements in the second row of A:Fetch the second and third elements in the second row of A:>> V = A(2, [2,3])>> V = A(2, [2,3])

Extract the entire second column:Extract the entire second column:>> X2 = A(:, 2)>> X2 = A(:, 2)

Fetch the entire third and fourth columns:Fetch the entire third and fourth columns:>> partOfB = A(:, [3,4])>> partOfB = A(:, [3,4])

Fetch the first and second elements in the second and third columns:Fetch the first and second elements in the second and third columns:>> anotherPartOfB = A([1,2], [2,3])>> anotherPartOfB = A([1,2], [2,3])

Page 103: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 103

Fetching Elements cont’dFetching Elements cont’d

3547

1821

0198

6745

A

How would you address to number 0?How would you address to number 0?

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

How about 2?How about 2?>> A(3,2)>> A(3,2)

Page 104: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 104

Fetching Elements cont’dFetching Elements cont’d

3547

1821

0198

6745

A

How can we extract the collection of numbers in the dotted box?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 That is, the numbers in the 1st through 3rd rows, 2nd through 4th

columns…columns…

Specify the row and column numbers by counting them…Specify the row and column numbers by counting them…

A(1:3, 2:4)A(1:3, 2:4)

Page 105: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 105

Setting ElementsSetting ElementsCreate an array A by the following:Create an array A by the following:

>> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]>> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]

Set the element at row two and column 4 to 100:Set the element at row two and column 4 to 100:

>> A(2,4) = 100;>> A(2,4) = 100;

Create a new array B that is identical to modified A, except that the Create a new array B that is identical to modified A, except that the

second and third columns are interchanged. second and third columns are interchanged.

>> B = A;>> B = A;

>> B(:,[2,3]) = A(:, [3,2])>> B(:,[2,3]) = A(:, [3,2])

The shape of the array to be set must be the same as the shape of the The shape of the array to be set must be the same as the shape of the

array that holds the new values.array that holds the new values.

Page 106: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 106

Built-in Functions Built-in Functions endend and and sizesize

Create an array A by the following:Create an array A by the following:

>> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]>> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]

Replace the last and next to last row/column elements with 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]>> A(end-1:end,end-1:end) = [100, 101; 200, 201]

For vectors, we had For vectors, we had lengthlength to return the number of elements. to return the number of elements.

For arrays, For arrays, sizesize built-in function is used: built-in function is used:

>> [numRows, numCols] = size(A)>> [numRows, numCols] = size(A)

Page 107: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 107

Synopsis for Setting ElementsSynopsis for Setting Elements

Array access operations (fetch and set) are directly Array access operations (fetch and set) are directly

analogous to vector access operations.analogous to vector access operations.

For array setting, the part of an array to be set and the For array setting, the part of an array to be set and the

elements which will be inserted must be the same shape.elements which will be inserted must be the same shape.

The colon may be used as an index element to indicate all.The colon may be used as an index element to indicate all.

end end is used in array access as it is used in vector access.is used in array access as it is used in vector access.

To determine the number of rows and columns in an array, To determine the number of rows and columns in an array,

use use sizesize..

Page 108: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 108

7-3 Transpose Applied to Arrays7-3 Transpose Applied to Arrays

Page 109: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 109

The Transpose OperatorThe Transpose OperatorThe transpose operator is used to flip an array. The transpose operator is used to flip an array.

More formally, if A is an NxM vector, then A' will be an 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). 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]>> D = [1,2,3,4; 10,11,12,13; 20, 21,22,23]

>> transposeD = D’>> transposeD = D’

The effect of applying the transpose operator to an array is The effect of applying the transpose operator to an array is

to flip rows and columns.to flip rows and columns.

What was a row is now a column, and what was a column What was a row is now a column, and what was a column

is now a row.is now a row.

Page 110: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 110

7-4 7-4 Array Built-in Functions, Array Built-in Functions, Operators, and ExpressionsOperators, and Expressions

Page 111: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 111

Built-in Functions and OperatorsBuilt-in Functions and Operators

The same types in Vectors exist – with new The same types in Vectors exist – with new

possibilitiespossibilities>> D = [1,10; 100,110]>> D = [1,10; 100,110]

>> sumOverColumns = sum(D,1)>> sumOverColumns = sum(D,1)

>> sumOverRows = sum(D,2)>> sumOverRows = sum(D,2)

Page 112: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 112

Cell-by-Cell OperatorsCell-by-Cell Operators

Arrays A and B are defined as: Arrays A and B are defined as: >> A = [2:4; 20:10:40]>> A = [2:4; 20:10:40]>> B = [1:3; 1:3]>> B = [1:3; 1:3]

Find cell-by-cell product of A and B:Find cell-by-cell product of A and B:>> A .* B>> A .* B

Find A raised to the power B, cell-by-cell:Find A raised to the power B, cell-by-cell:>> A .^ B>> A .^ B

Find A/B, cell-by-cell:Find A/B, cell-by-cell:>> A ./ B>> A ./ B

B

A

A

BA./B stands for , whereas B./A stands for , A./B stands for , whereas B./A stands for , cell-by-cellcell-by-cell

Page 113: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 113

Example Problem 1Example Problem 1Cell-by-Cell OperatorsCell-by-Cell OperatorsThe ABC electronics factory makes four different items: a The ABC electronics factory makes four different items: a

48-inch HDTV, a 32-inch regular TV, a computer called 48-inch HDTV, a 32-inch regular TV, a computer called the M2 model, and a DVD player called the R2 model. the M2 model, and a DVD player called the R2 model.

Compute:Compute:

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

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

Page 114: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 114

Example Problem cont’dExample Problem cont’d

Find by hand quarter 1 to material costs from Find by hand quarter 1 to material costs from the HDTV product line.the HDTV product line.

532 * $892 = $474,544.532 * $892 = $474,544.

Think through the problem statement.Think through the problem statement.

This problem is not conceptually difficult but is This problem is not conceptually difficult but is tedious.tedious.

MATLAB provides a better way…MATLAB provides a better way…

Page 115: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 115

Matrix OperatorsMatrix Operators

Matrix multiplication operation is defined as:Matrix multiplication operation is defined as:

1.1. The number of columns in A must be equal to the The number of columns in A must be equal to the number of rows in B. Otherwise, this is not a legal number of rows in B. Otherwise, this is not a legal operation.operation.

2.2. Assuming Rule 1 is met the number of rows in C will be Assuming Rule 1 is met the number of rows in C will be equal to the number of rows in A.equal to the number of rows in A.

3.3. Likewise, the number of columns in C will be equal to Likewise, the number of columns in C will be equal to the number of columns in B.the number of columns in B.

Page 116: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 116

(2,1) (2,2)

(1,1) (1,2)

Matrix MultiplicationMatrix Multiplication

11 22

33 44

99 77

88 66

2 X 2 2 X 2

=X

2 X 2

=

1*9 + 2*81*9 + 2*8

3*9 + 4*83*9 + 4*8

1*7 + 2*61*7 + 2*6

3*7 + 4*63*7 + 4*6

2525 1919

5959 4545

Page 117: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 117

Example Problem 2Example Problem 2Matrix OperatorsMatrix Operators

67

89

35

61

42

,

BA

where

BAfind

Page 118: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 118

Revisiting Example Problem 1Revisiting Example Problem 1

The ABC electronics factory makes four different items: a The ABC electronics factory makes four different items: a 48-inch HDTV, a 32-inch regular TV, a computer called 48-inch HDTV, a 32-inch regular TV, a computer called the M2 model, and a DVD player called the R2 model. the M2 model, and a DVD player called the R2 model.

Compute:Compute:

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

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

Page 119: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 119

Example Problem cont’dExample Problem cont’d

=?

Page 120: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 120

Example Problem 3Example Problem 3Matrix OperatorsMatrix Operators

Page 121: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 121

Matrix Left DivisionMatrix Left Division

A linear system of equations can be modeled as: A linear system of equations can be modeled as:

132

216

932

zyx

zyx

zyx

1

21

9

321

161

132

z

y

x

In other words…In other words… yxA

Page 122: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 122

Matrix Left Division cont’dMatrix Left Division cont’d

Can be solved for x as follows:Can be solved for x as follows:

Or in MatLab by left division:Or in MatLab by left division:

yxA

yAx 1

yAx

\

Page 123: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 123

Example Problem 4Example Problem 4Matrix Left DivisionMatrix Left DivisionJeanie, Juan, and Alexander each have some fruit. Each has a Jeanie, Juan, and Alexander each have some fruit. Each has a

number of apples, oranges, and pears. number of apples, oranges, and pears. All apples have the same weight, all oranges have the same All apples have the same weight, all oranges have the same

weight, and all pears have the same weight. weight, and all pears have the same weight. Jeanie has 3 apples, 2 oranges, and 1 pear. The total weight of Jeanie has 3 apples, 2 oranges, and 1 pear. The total weight of

fruit that Jeanie has is 52 ounces. fruit that Jeanie has is 52 ounces. Juan has 2 apples, 3 oranges, and 1 pear. The total weight of Juan has 2 apples, 3 oranges, and 1 pear. The total weight of

fruit that Juan has is 50 ounces. fruit that Juan has is 50 ounces. Alexander has 1 apple, 2 oranges, and 3 pears. The total Alexander has 1 apple, 2 oranges, and 3 pears. The total

weight of fruit that Alexander has is 56 ounces.weight of fruit that Alexander has is 56 ounces.

What is the weight of each apple, orange, and pear?What is the weight of each apple, orange, and pear?

Page 124: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 124

Example Problem 5Example Problem 5Relational and Logical Relational and Logical OperatorsOperators

1.1. Using the find function, find and display:Using the find function, find and display:a.a. the row and column numbers of elements in A that are less than the row and column numbers of elements in A that are less than

zerozero

b.b. elements that are less than zeroelements that are less than zero

c.c. elements that are greater than -4 but less than 4elements that are greater than -4 but less than 4

2.2. Using the all or any functions, determine:Using the all or any functions, determine:a.a. if all elements in A are greater than -8if all elements in A are greater than -8

b.b. if any elements in A are less than -5if any elements in A are less than -5

Page 125: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 125

SynopsisSynopsisArrays are indexed by giving the row and column locations.Arrays are indexed by giving the row and column locations.

All cell-by-cell operations are generalizations of the corresponding All cell-by-cell operations are generalizations of the corresponding vector operation.vector operation.

Matrix multiplication can be very advantageous when the problem you Matrix multiplication can be very advantageous when the problem you are solving involves a sum of scalar multiplication operations. are solving involves a sum of scalar multiplication operations.

Matrix left division is often used to solve systems of linear simultaneous Matrix left division is often used to solve systems of linear simultaneous equations. equations.

Values in an array that meet some relational test may be extracted using Values in an array that meet some relational test may be extracted using find as an indexing term.find as an indexing term.

Two output values are returned when the find function is applied to an 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 array: a vector of row index values and a corresponding vector of column index values.index values.

Page 126: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Conditional and Iterative Conditional and Iterative ProgrammingProgramming

Chapter 7Chapter 7

Page 127: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 127

8-1 Program Flow8-1 Program Flow

1.1. Straight Line CodeStraight Line Code

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

Page 128: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 128

Program Flow cont’dProgram Flow cont’d

2.2. Conditional CodeConditional Code

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

testYESNO

Page 129: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 129

Program Flow cont’dProgram Flow cont’d

3.3. Iterative codeIterative code

Execute the same block of code again and again …

repeat…

Page 130: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 130

Synopsis for Program Flow Synopsis for Program Flow TypesTypes

There are three major types of program control: straight There are three major types of program control: straight line control, conditional control, and iterative control.line control, conditional control, and iterative control.Programming constructs for conditional control and Programming constructs for conditional control and iterative control should be considered “modules,” meaning iterative control should be considered “modules,” meaning there is one point of entrance into the construct and one there is one point of entrance into the construct and one point of exit. point of exit. Straight line code executes in the order it is written in a Straight line code executes in the order it is written in a program.program.Conditional code executes one alternative of a number of Conditional code executes one alternative of a number of possibilities, selecting the alternative to run based on a possibilities, selecting the alternative to run based on a relational/logical test of program variables.relational/logical test of program variables.Iterative code executes the same block of code a number of Iterative code executes the same block of code a number of times.times.

Page 131: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 131

8-2 Iterative Program Flow: 8-2 Iterative Program Flow: FORFOR

General form:General form:

A FOR loop must end with a line containing A FOR loop must end with a line containing end.end.

Page 132: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 132

Questions for the Iterative CaseQuestions for the Iterative Case

How many times does How many times does it repeat?it repeat?

What controls how What controls how many times it repeats?many times it repeats?

How are you going to How are you going to set parameter values in set parameter values in a handy way for each a handy way for each “pass”“pass”

repeat…repeat…

Page 133: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 133

Code to be repeated

Values taken on by changing var

Name of var that changes

Iteration over Elements of a Iteration over Elements of a Row VectorRow Vector

mySum = 0;mySum = 0;forfor itemThisTime = [1 0 -5 78] itemThisTime = [1 0 -5 78]

mySum = mySum + itemThisTime;mySum = mySum + itemThisTime;display(itemThisTime);display(itemThisTime);display(mySum );display(mySum );disp('====')disp('====')

endend

disp('***********************')disp('***********************')mySummySum

Page 134: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 134

Code to be repeated

Values taken on by changing var

Name of var that changes

Iteration over Columns of an Iteration over Columns of an ArrayArray

sumColumnProducts = 0;sumColumnProducts = 0;forfor oneCol = [1 0 -5 78; 61 9 44 10] oneCol = [1 0 -5 78; 61 9 44 10]

sumColumnProducts = sumColumnProducts + sumColumnProducts = sumColumnProducts + oneCol(1)*oneCol(2);oneCol(1)*oneCol(2);display(oneCol);display(oneCol);display(sumColumnProducts);display(sumColumnProducts);disp('====')disp('====')

endend

disp('***********************')disp('***********************')sumColumnProductssumColumnProducts

Page 135: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 135

Nested FOR LoopsNested FOR Loops

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

for j=1:nColsfor j=1:nColscellSum(i,j)=A(i,j)+B(i,j);cellSum(i,j)=A(i,j)+B(i,j);

endendendend

Page 136: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 136

Synopsis for FORSynopsis for FOR

FOR loops are used in cases where you need more control FOR loops are used in cases where you need more control over computations than allowed in cell-by-cell operations.over computations than allowed in cell-by-cell operations.FOR loops start with a code line that begins with keyword FOR loops start with a code line that begins with keyword

forfor and end with keyword and end with keyword endend..

FOR loops iterate over a code block body using successive FOR loops iterate over a code block body using successive values of supplied vector or array.values of supplied vector or array.If a FOR loop is supplied with an array, then successive If a FOR loop is supplied with an array, then successive values of the columns of the array are set to the value of values of the columns of the array are set to the value of the loop variable.the loop variable.To understand a FOR loop, a good strategy is to “step To understand a FOR loop, a good strategy is to “step through” the loop.through” the loop.

Page 137: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 137

8-4 Conditional Program Flow8-4 Conditional Program Flow

Form 1: IFForm 1: IFif <conditions>

<statements>end;

J&T Computers is planning to give a J&T Computers is planning to give a $3,000 holiday bonus to every $3,000 holiday bonus to every employee provided ALL employee provided ALL employees have a performance employees have a performance evaluation higher than 3/5. evaluation higher than 3/5.

For the dataset, find if bonus will be For the dataset, find if bonus will be given.given.

Employee Numbers, Employee Numbers,

Performance Ratings, SalariesPerformance Ratings, Salaries

Page 138: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 138

Conditional Program Flow Conditional Program Flow cont’dcont’d

Form 2: IF/ELSEForm 2: IF/ELSE

if <conditions><statements>

else<statements>

end;

Instead of giving bonus to all Instead of giving bonus to all employees, consider the employees, consider the following scenario:following scenario:

every employee with aevery employee with aperformance rating of 4 or 5 gets a 5 performance rating of 4 or 5 gets a 5

percent holiday bonus while all percent holiday bonus while all other employees will get a 2 other employees will get a 2 percent bonus.percent bonus.

Employee Numbers, Employee Numbers,

Performance Ratings, SalariesPerformance Ratings, Salaries

Page 139: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 139

Conditional Program Flow Conditional Program Flow cont’dcont’d

Form 3: IF/ELSEIFForm 3: IF/ELSEIF

if <conditions><statements>

elseif<statements>

end;

New scenario:New scenario:Employees with performanceEmployees with performanceratings of 5 get a 4% bonus, those ratings of 5 get a 4% bonus, those

with performance ratings of 4 get with performance ratings of 4 get aa

2% bonus, and those with 2% bonus, and those with performance ratings of 3 get a 1% performance ratings of 3 get a 1% bonus.bonus.

Employee Numbers, Employee Numbers,

Performance Ratings, SalariesPerformance Ratings, Salaries

Page 140: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 140

Conditional Program Flow Conditional Program Flow cont’dcont’d

Form 4: Form 4: IF/ELSEIF/ELSEIF/ELSEIF/ELSE

if <conditions><statements>

elseif<statements>

else<statements>

end;

One last scenario:One last scenario:employees with performance ratings employees with performance ratings

of 5 get a 4% bonus, those with of 5 get a 4% bonus, those with performance ratings of 4 get a 3% performance ratings of 4 get a 3% bonus, those with performance bonus, those with performance ratings of 3 get a 2% bonus, and ratings of 3 get a 2% bonus, and everyone else gets a 1% bonuseveryone else gets a 1% bonus Employee Numbers, Employee Numbers,

Performance Ratings, SalariesPerformance Ratings, Salaries

Page 141: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 141

Sample ProblemSample Problem

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

When will I be a millionaire?When will I be a millionaire?

How much savings will I have after 10 years?How much savings will I have after 10 years?

Page 142: An Introduction To Technical Problem Solving with MATLAB v.7 Jon Sticklen, PhD M. Taner Eskil, PhD

Intro to Technical Problem Solving with MATLAB v.7 142

SynopsisSynopsisIF-THEN-ELSE can be used to express conditional program IF-THEN-ELSE can be used to express conditional program control. It is best understood in four distinct forms.control. It is best understood in four distinct forms.1.1. IF: In this form, one relational/logical test exists. During execution, IF: In this form, one relational/logical test exists. During execution,

if the test results in true, then the commands in the following block 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.are run. If the test results in false, then the commands are not run.

2.2. IF-ELSE: This form performs a relational/logical test and, if true, IF-ELSE: This form performs a relational/logical test and, if true, then runs a set of commands. If false, an alternative set of then runs a set of commands. If false, an alternative set of commands is run.commands is run.

3.3. IF-ELSEIF: There can be multiple ELSEIF clauses. Only one (at 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 most) code block following a test will be run, which will be the one following the first test that results in true.following the first test that results in true.

4.4. IF-ELSEIF-ELSE: This form is a combination of the second and IF-ELSEIF-ELSE: This form is a combination of the second and third forms.third forms.

The key to effective use is to correctly match the problem The key to effective use is to correctly match the problem situation you have with one of the appropriate four forms.situation you have with one of the appropriate four forms.