intro tech matlab
TRANSCRIPT
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 1/142
An Introduction To
Technical Problem Solving
with MATLAB v.7
Jon Sticklen, PhD
M. Taner Eskil, PhD
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 2/142
IntroductionChapter 1
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 3/142
Intro to Technical Problem Solving with MATLAB v.7 3
Introduction
What is Technical Problem Solving?
The Path to Becoming a Good Technical
Problem Solver
What You Must Do to Master the Material
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 4/142
Intro to Technical Problem Solving with MATLAB v.7 4
1-1 What is Technical Problem
Solving?Good common sense applied to technical
problems
Quantitative in nature
Basis for making many decisions
Rooted in numerical calculations
Decompose the problem
Mainstay of what an engineer does
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 5/142
Intro to Technical Problem Solving with MATLAB v.7 5
1-2 The Path to Becoming a
Good Technical Problem Solver Master the conceptual subject matter of a
given technical area
Demonstrate what you have learned
Master the tools of the trade
MATLAB
Mathematica
MathCad
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 6/142
Intro to Technical Problem Solving with MATLAB v.7 6
1-3 What You Must Do to Master
the MaterialBe prepared to spend substantial time
learning this material
Read assigned sections of the text with
MATLAB at your side
Work the problems hands-on
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 7/142
A Framework for
Technical Problem SolvingChapter 2
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 8/142
Intro to Technical Problem Solving with MATLAB v.7 8
A Framework for Technical
Problem Solving
Steps in a Framework for Technical
Problem Solving
An Example Using the Framework
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 9/142
Intro to Technical Problem Solving with MATLAB v.7 9
2-1 Steps in a Framework for
Technical Problem SolvingStep 1: Refine and Structure
Arrive at a precise problem statement
Give the problem initial structure:
Problem inputs
Computational output
Step 2: Make a sketch or diagramVisualize the physical situation
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 10/142
Intro to Technical Problem Solving with MATLAB v.7 10
2-1 Steps in a Framework for
Technical Problem SolvingStep 3: Assemble and Organize
What do you need to know to solve the
problem?Get the needed information:
Internet search engines such as Yahoo or Google
LibraryStep 4: Simplify
Find if there are suitable approximations
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 11/142
Intro to Technical Problem Solving with MATLAB v.7 11
2-1 Steps in a Framework for
Technical Problem SolvingStep 5: Decompose
Simpler problems
Reduce the complexity of the solution
Step 6: Dimensional Analysis
Are the mathematical relationships you intend
to apply in your solution flawed?Substitute the units for each variable and
algebraically simplify
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 12/142
Intro to Technical Problem Solving with MATLAB v.7 12
2-1 Steps in a Framework for
Technical Problem SolvingStep 7: Compute and Discuss
Perform the computations needed to obtain a
solutionUse a computational tool such as MATLAB
Examine and understand the results
Be ready to explain them!
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 13/142
Intro to Technical Problem Solving with MATLAB v.7 13
2-2 An Example Using the
Framework Problem:
What is the optimum firing angle we should set
for a catapult whose purpose is to hurl haybales to a herd of starving caribou, given the
initial velocity of hay bales as they exit the
catapult?
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 14/142
Intro to Technical Problem Solving with MATLAB v.7 14
2-2.1 Refine and Structure
Clarify:Think about the problem
The ultimate source of information is the person setting
the problemRefine:
What is the firing angle of a catapult in order to hurl projectiles a maximum horizontal distance given the
initial velocity of the object ?What are the Input(s) and Output(s)?
Initial speed, angle, maximized distance
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 15/142
Intro to Technical Problem Solving with MATLAB v.7 15
2-2.2 Sketch or Diagram
What is the firing angle measured from the
horizontal we should set for a catapult to hurl
projectiles a maximum horizontal distance given
the initial velocity of the object?
h
D
L1
L2
g
s
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 16/142
Intro to Technical Problem Solving with MATLAB v.7 16
2-2.3 Background Knowledge
For our example:
General knowledge of physics
General knowledge of one way in whichoptimizing problems may be solved
Seek the value of the firing angle f that
maximizes the total horizontal distance D traveled given an initial speed of the hay
bale as it comes out of the catapult
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 17/142
Intro to Technical Problem Solving with MATLAB v.7 17
2-2.4 Assumptions and
Approximations
Many times in technical problem solving, the pathto a solution leads to making assumptions aboutthe problem and then solving the simplifiedversion of the problem.
Negligible air resistance
No difference between a hay bale and a snowball
Be aware of the assumptions you are making andcommunicate them to the person who originallyset the problem for you.
Importance of good documentation
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 18/142
Intro to Technical Problem Solving with MATLAB v.7 18
2-2.5 Decomposing /Recursive
Structuring
Break the problem into pieces, each with its
own well defined input and output
Develop technical solutions for each piece
Work backwards to find what you need
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 19/142
Intro to Technical Problem Solving with MATLAB v.7 19
2-2.6 Dimensional Analysis
g
s
Do )cos()sin(22 f f
2
2
s
ft
s
ft
ft
f t f t
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 20/142
Intro to Technical Problem Solving with MATLAB v.7 20
2-2.7 Putting It All Together
2
max 031.0 os D
f (degrees) 0 10 20 30 40
Unit Distance (feet) 0.0000 0.0107 0.0201 0.0271 0.0308
f (degrees) 90 80 70 60 50
Unit Distance (feet) 0.0000 0.0107 0.0201 0.0271 0.0308
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 21/142
Intro to Technical Problem Solving with MATLAB v.7 21
2-2 Synopsis
Identify input and output variables correctly
Create a sketch of the physical situation
Generalize the problem
Apply general background knowledge
General approach to optimization problems
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 22/142
MATLAB Basics: ScalarsChapter 3
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 23/142
Intro to Technical Problem Solving with MATLAB v.7 23
Scalars
The First Time You Bring Up MATLAB
MATLAB as a Calculator for Scalars
Fetching and Setting Scalar Variables
MATLAB Built-in Functions, Operators,
and Expressions
Problem Sets for Scalars
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 24/142
Intro to Technical Problem Solving with MATLAB v.7 24
3-1 The First Time You Bring Up
MATLAB
Basic windows in MATLAB are:
Command - executes single-line commands
Workspace - keeps track of all defined variables
Command History - keeps a running record of all singleline programs you have executed
Current Folder - lists all files that are directly available forMATLAB use
Array Editor - allows direct editing of MATLAB arrays
Preferences - for setting preferences for the display of results, fonts used, and many other aspects of howMATLAB looks to you
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 25/142
Intro to Technical Problem Solving with MATLAB v.7 25
3-2 MATLAB as a Calculator for
Scalars
A scalar is simply a number…
In science the term scalar is used as opposed to a vector,
i.e. a magnitude having no direction.
In MATLAB, scalar is used as opposed to arrays, i.e. a
single number .Since we have not covered arrays (tables of numbers)
yet, we will be dealing with scalars in MATLAB.
,4,
7
22,5.3
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 26/142
Intro to Technical Problem Solving with MATLAB v.7 26
Using the Command History
Window
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 27/142
Intro to Technical Problem Solving with MATLAB v.7 27
3-3 Fetching and Setting Scalar
Variables
Think of computer
variables as named
containers.We can perform 2
types of operations
on variables:
we can set the value held in the container: x = 22
we can look at the value held in the container: x
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 28/142
Intro to Technical Problem Solving with MATLAB v.7 28
The Assignment Operator (=)
The equal sign is the assignment operator inMATLAB.
>> x = 22
places number 22 in container x
How about:
>> x = x + 1
Note the difference between the equal sign inmathematics and the assignment operator inMATLAB!
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 29/142
Intro to Technical Problem Solving with MATLAB v.729
3-3.2 An Example - Setting
Variables for the Hay Bale Problem
clear deletes variables from workspace, youshould use it before starting new work
The percent symbol is used for putting reminders
(comments) for ourselves, ignored by MATLABCommand lines ending with semicolon do not
display the results.
>> clear>> accelGravity = 32; % units: ft/sec/sec>> speedInitial = 50; % units: ft/sec>> phi = 10; % units: degrees
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 30/142
Intro to Technical Problem Solving with MATLAB v.730
3-4 MATLAB Built-in Functions,
Operators, and Expressions
MATLAB comes with a large number of built-
in functions (e.g.. sin, cos, tan, log10, log, exp)
A special subclass of often-used MATLABfunctions is called operators
Assignment operator (=)
Arithmetic operators (+, -, *, /, ^)
Relational operators (<, <=, = =, ~=, >=, >)
Logical operators (&, |, ~)
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 31/142
Intro to Technical Problem Solving with MATLAB v.731
Example – Arithmetic Operators
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 32/142
Intro to Technical Problem Solving with MATLAB v.732
Example – Relational and
Logical Operators
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 33/142
Intro to Technical Problem Solving with MATLAB v.733
3-4.2 Rules for Forming
Expressions
MATLAB expressions consist of:
Numerical values or variables
Logical values or variablesLegal applications of MATLAB functions or
operators
A combination of MATLAB expressions
What is the error in the following MATLABexpression?
>> sin(pi/2, pi/8)
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 34/142
Intro to Technical Problem Solving with MATLAB v.734
Order of Precedence
If two operators are at
the same level of
precedence, the
evaluation is carried out
from left to right
An Example – Compute
for x = 4, y = 2
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 35/142
Intro to Technical Problem Solving with MATLAB v.735
Applying Scalar Computations to
a Problem
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 36/142
Intro to Technical Problem Solving with MATLAB v.736
Synopsis for Chapter 3A MATLAB variable can be thought of as a named container. The value of aMATLAB variable then is the contents of the box.
Setting the variable value is done using the assignment operator; fetching the
value of a variable is done by typing the name of the variable.
In MATLAB the type of a variable is defined by the way the variable is used.
Scalars are simple numbers.
Logical values can be TRUE (any non-zero number) or FALSE (0).
MATLAB operators are a special subclass of MATLAB built-in functions.
Arithmetic operators take numerical variables as input and output a numerical
result.
Relational operators take numerical variables as input and output a logical
result.
Logical operators take logical variables as input and output a logical result.
MATLAB expressions are blueprints for performing computations.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 37/142
Saving MATLAB Work
Chapter 4
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 38/142
Intro to Technical Problem Solving with MATLAB v.738
Saving MATLAB Work
The MATLAB “Current Directory”
Saving MATLAB Commands in Script
Files
Saving MATLAB Commands in User-
Defined Function Files
Testing and Debugging MATLAB Scriptand Function Files
Problem Sets for “Saving Your Work”
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 39/142
Intro to Technical Problem Solving with MATLAB v.739
4-1 The MATLAB Current
Directory
It is the default folder MATLAB will save files
It is the first folder MATLAB will attempt to load files
It may be changed interactively using the Current
Directory Window or built-in commands
MATLAB starts
up with the
default folderconnected
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 40/142
Intro to Technical Problem Solving with MATLAB v.740
4-2 Saving MATLAB Commands
in Script Files
Script files are lines of code just like you
would type in to the Command Window
It is good programming practice to includecomments for:
The location of the file
Variables used in the script but defined outsideResults produced by the script
Units of values calculated in the script
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 41/142
Intro to Technical Problem Solving with MATLAB v.741
An Example – The Water Tower
Problem
compute water tower cost
and volume
cylinder caped by
hemisphere
diameter and height of
cylinder known
known cost/m2 for
hemisphere and forcylinder
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 42/142
Intro to Technical Problem Solving with MATLAB v.742
Synopsis for MATLAB Scripts
A script file consists of groups of MATLABcommands bundled together into a module
Scripts files have a DOT-M extension
When executing inside a script file, allvariables in the workspace are available
Variables created in a script are available at
the Command Window and in other scriptsMaking a sketch of a problem is important
in making the problem context concrete
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 43/142
Intro to Technical Problem Solving with MATLAB v.743
4-3 Saving MATLAB Commands
in User-Defined Function Files
Scripts - these are lines of code exactly like
you could type in to the command window
Functions - are “computational boxes.” Yougive them a set of input values, and they
calculate a set of output values. Purpose of
functions is the same as the purpose of scripts
+
modularize your code
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 44/142
Intro to Technical Problem Solving with MATLAB v.744
Central Points… The only way of getting a variable‟s value into a
function is for that variable to be input to the
function.
The only way of getting a value out of a function is
for that variable to be output from the function.A variable used inside a function that is not an input
or an output variable is not visible outside the
function.
An example:
>> x = pi;
>> y = sin(x)
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 45/142
Intro to Technical Problem Solving with MATLAB v.745
Syntax of a User Defined Function
Functions are saved in DOT M files - just
like the script files
Same rules for the connected directoryapplies
First line of the file defines
Name of the functionInput variable(s)
Output variable(s)
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 46/142
Intro to Technical Problem Solving with MATLAB v.746
Defining a function – the first line
function <outputVars> = <function name> (<inputVars> )
Keyword - has to beexactly 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
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 47/142
Intro to Technical Problem Solving with MATLAB v.747
Linkage Between Actual and
Formal 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 thecalling line (a,b)
2. The function “runs”
3. The output variables in the function are given back to the callingprogram’s variable.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 48/142
Intro to Technical Problem Solving with MATLAB v.748
Comments in Functions
There are no uniformly agreed upon rules for
inserting comments into functions
It is always good programming practice to include
comment lines indicating:
the purpose of the function
the inputs to the function
the outputs from the functionany assumptions
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 49/142
Intro to Technical Problem Solving with MATLAB v.749
Examples
function <outputVars> = <function name> (<inputVars> )
For each of the following function definitions,
how many input and output variables are
there?
function x = myFun1
function z = myFun2(y)
function out33 = myFun3(x,y)
function [a,b] = myFun4(q,r)
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 50/142
Intro to Technical Problem Solving with MATLAB v.7
50
Examples
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 51/142
Intro to Technical Problem Solving with MATLAB v.7
51
Examples
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 52/142
Intro to Technical Problem Solving with MATLAB v.7
52
Synopsis for User-Defined
Functions
The workspace of a function is insulated from the outside.
When a MATLAB function is called, a linkage is made
between the actual parameters in the call and the formal
parameters in the function definition.
The number of actual input parameters must be the same as
the number of formal input parameters. This is also valid
for the output parameters.
The first line of a MATLAB function begins with thekeyword function, and the rest of the first line looks like an
assignment statement.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 53/142
Intro to Technical Problem Solving with MATLAB v.7
53
4-4 Testing and Debugging
MATLAB Script and Function Files
Types of errors in programs:
Syntax errors
Results from incorrect application of MATLAB rulesMATLAB aborts the computation and points of the
error
Runtime errors
Results from incorrect logic and MATLAB not doingwhat you intend
For this type error MATLAB debugging facilities are
useful
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 54/142
Intro to Technical Problem Solving with MATLAB v.7
54
Examples
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 55/142
Intro to Technical Problem Solving with MATLAB v.7
55
Examples
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 56/142
Intro to Technical Problem Solving with MATLAB v.7
56
Synopsis for Debugging
Identify the set of inputs you will use for the test
Determine what you expect for each of the test
input sets to produceCompare what you expect to what MATLAB
produces to identify runtime errors in the function
Identify and correct the line(s) of code that arecausing the runtime error
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 57/142
Vector Operations
Chapter 5
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 58/142
Intro to Technical Problem Solving with MATLAB v.7
58
Vector Operations
Vector Creation
Accessing Vector Elements
Row Vectors and Column Vectors, and theTranspose Operator
Vector Built-in Functions, Operators, and
Expressions
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 59/142
Intro to Technical Problem Solving with MATLAB v.7
59
5-1 Vector Creation
Vectors are defined in square brackets;temperaturesMonThu = [32 31 29 33];
temperaturesFriSat = [35 33];
You can concatenate a vector with a scalar;
temperaturesFriSun = [35 33 27];or concatenate 2 vectors;
weeklyTemperatures = [temperaturesMonThu, temperaturesFriSun];
To find the size of a vector, we use length;numTemperatures = length(weeklyTemperatures);
We could find the average temperature by typing;avgTemperature = mean(dailyTemperatures)
or by using sum and length;totalTemperature = sum(dailyTemperatures)/length(dailyTemperatures);
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 60/142
Intro to Technical Problem Solving with MATLAB v.7
60
Some Useful Vector Functions
brackets (e.g. [27 36 41]): Creates vectors.
colon operator (e.g. [0:5:30]): Creates linearly spaced vectors.
linspace (e.g. linspace(0,100,21)): Creates linearly spaced vectors.
length (e.g. length([0:5:30])): Finds the length of a vector.
zeros (e.g. zeros(1,5)): Creates vectors filled with zeroes.
ones (e.g. ones(1,5): Creates vectors filled with ones.
sum (e.g. sum([5 3 6 2])): Sums up the contents of a vector.
sort (e.g. sort([5 3 6 2])): Sorts the contents of a vector.
mean (e.g. mean([5 3 6 2])): Finds the average of contents.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 61/142
Intro to Technical Problem Solving with MATLAB v.7
61
5.2 – Accessing Vector Elements –
Examples
1. Create a row vector x consisting of the numbers in the orderedset: {1 4 7 10} using the colon operator.
x = [1:3:10]
2. Set a variable y to be the length of x.
y = length(x)
3. Set variable y to be the 1st element of x.
y = x(1)
4. Set variable y to be the 1st, 2nd, and 3rd elements of x.
y = x([1,2,3]) OR y = x(1:3)
A l
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 62/142
Intro to Technical Problem Solving with MATLAB v.7
62
Accessing Vector Elements –
Example cont’d.
5. Set variable y to be the 3rd through the last element of x - and do sosuch that your solution works no matter how long x is.
y = x(3:end)
6. Set variable y to be the next-to-last and last element of x - and do sosuch that your solution works no matter how long x is.
y = x([end-1,end])
7. Change the 2nd element of x to be 3.
x(2) = 3
8. Change the 2nd element of x to be 102 and the 4th element of x be205.
x([2,4]) = [102, 205]
S i f F hi d S i
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 63/142
Intro to Technical Problem Solving with MATLAB v.7
63
Synopsis for Fetching and Setting
Elements in VectorsAccess to whole vector is similar to scalar access.
Accessing element(s) in a vector is done by indexing intothe vector.
To delete element(s) in a vector, empty square brackets are
used.To find the length of a vector V, use the length built-infunction length(V).
When setting elements of a vector, the number of elements
being set must be equal to the number of elements in thevector on the right hand side of the assignment operation.The exception is that a scalar on the right-hand side can beused to set multiple vector elements.
5 3 R V d C l
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 64/142
Intro to Technical Problem Solving with MATLAB v.7
64
5-3 Row Vectors and Column
Vectors, and the Transpose Operator Row and column vectors are represented as singlerows and columns of values, respectively.
When creating a column vector with square
brackets, you may use the semicolon operator:temp = [35; 33; 27];
or you may use the transpose operator;temp = [35 33 27]‟;
When creating an equally spaced column vector,you need to use the transpose operator;springConstants = [10:10:100]‟;
springConstants = linspace(10,100,10)‟;
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 65/142
Intro to Technical Problem Solving with MATLAB v.7
65
5-4 Vector Built-in Functions,
Operators, and Expressions
S l P bl V t B ilt
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 66/142
Intro to Technical Problem Solving with MATLAB v.7
66
Sample Problem – Vector Built-
in Functions
S l P bl V t
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 67/142
Intro to Technical Problem Solving with MATLAB v.7
67
Sample Problem – Vector
Arithmetic Operators
S l P bl V t
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 68/142
Intro to Technical Problem Solving with MATLAB v.7
68
Sample Problem – Vector
Arithmetic Operators
S l P bl V t
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 69/142
Intro to Technical Problem Solving with MATLAB v.7
69
Sample Problem – Vector
Arithmetic Operators
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 70/142
Intro to Technical Problem Solving with MATLAB v.7
70
Vector Relational Operators
Think of them as comparing numbers…
<, >, = =, >=, <=
A relational operator can be used tocompare the values of two variables
a>b
But… remember MATLAB is for matrices
what are you testing?
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 71/142
Intro to Technical Problem Solving with MATLAB v.7
71
What are you testing?
Number (scalar) vs. Number
Number vs. Vector (or Matrix)
A scalar is compared to each element of the vector…5<[1:10]
Vector vs. Vector
Each corresponding element of the two vectors is
compared…
[1:10]<=[10:-1:1]
Sample Problem Vector
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 72/142
Intro to Technical Problem Solving with MATLAB v.7
72
Sample Problem – Vector
Relational Operators
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 73/142
Intro to Technical Problem Solving with MATLAB v.7
73
Vector Logical Operators
They operate on the results of relational operators
How many elements in vector x are in range(6,10)?
How many elements in x are… greater than 6
AND
… less than 10?
We use logical operators… AND (&), OR (|), NOT (~)
any, all
Sample Problem Vector
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 74/142
Intro to Technical Problem Solving with MATLAB v.7
74
Sample Problem – Vector
Logical Operators
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 75/142
Intro to Technical Problem Solving with MATLAB v.7
75
Synopsis for Vector Operators
There are functions that work in a cell-by-cell fashion (like sin) and functionsthat aggregate (like sum).
Cell-by-cell vector operators apply the indicated operation to thecorresponding elements of the two vectors.
For cell-by-cell operations, the two arguments must be the same type of vector(row or column) and be of the same length, or one of the arguments must be a
scalar.Cell-by-cell vector operators include the classes (assignment, colon andtranspose operators), the vector arithmetic cell-by-cell operators (Table 5-2),the vector relational operators (Table 5-4), and vector cell-by-cell logicaloperators (Table 5-5).
Logical computations are extended via built-in logical functions (Table 5-6).
The built-in logical function find is useful because it enables a type of content
addressing.The operator precedence table was updated to include new possibilities (Table5-7).
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 76/142
2-D Plotting and Help in
MATLABChapter 6
2 D Plotting and Help in
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 77/142
Intro to Technical Problem Solving with MATLAB v.7
77
2-D Plotting and Help in
MATLAB
Using EZPLOT to Plot Functions
Using Vectors to Plot Numerical Data
Overlay plots and subplots
Other 2-D plot types in MATLAB
Problem Sets for 2-D Plotting
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 78/142
Intro to Technical Problem Solving with MATLAB v.7
78
6-1 Using EZPLOT to Plot
Functions
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 79/142
Intro to Technical Problem Solving with MATLAB v.7
79
Getting Help
You can‟t possibly learn everything there is
to know about MATLAB,
… and you don‟t need to. It is crucial to develop the ability to
augment your knowledge in MATLAB
toward accomplishing a given task.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 80/142
Intro to Technical Problem Solving with MATLAB v.7
80
Getting Help cont’d
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 81/142
Intro to Technical Problem Solving with MATLAB v.7
81
Getting Help cont’d
Click the tab in the navigation pane labeled
Search.
Then type into the Search field the name ezplot.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 82/142
Intro to Technical Problem Solving with MATLAB v.782
Using EZPLOT to Plot Functions
There are three forms of ezplot:
f(x) e.g., f(t) = 3e-2tcos(5t)
ezplot('3*exp(-2*t)*cos(5*t)')f(t), g(t) e.g., f(t) = 3t2 + 2; g(t) = sin(5t)
ezplot('3*t^2 + 2', 'sin(5*t)')
f(x,y) = 0 e.g., f(x,y) = 3xy + y2 + 55 = 0
ezplot('3*x*y + y^2 + 55',[-30,30,-20,20])
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 83/142
Intro to Technical Problem Solving with MATLAB v.783
Sample Problem - EZPLOT
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 84/142
Intro to Technical Problem Solving with MATLAB v.784
Graphing with MATLAB
Use ezplot to make a quick and dirty chart of functions.
Optional arguments allow changing the defaultfunctional domain [-2π, 2π].
Use xlabel , ylabel , and title built-in functions torefine labeling the plots made by ezplot.
When needed, use grid to activate a grid on a plotcreated.
If you would like to keep the existing graph andgenerate a new one, use figure.
6-2 Using Vectors to Plot
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 85/142
Intro to Technical Problem Solving with MATLAB v.785
6-2 Using Vectors to Plot
Numerical Data
Mostly from observed data - your goal is to understand therelationship between the variables of a system.
Determine the independent and dependent variables and plot:speed = 20:10:70;
stopDis = [46,75,128,201,292,385];
plot(speed, stopDis, '-ro') % note the „-ro‟ switch
Don‟t forget to properly label your graphs: title('Stopping Distance versus Vehicle Speed', 'FontSize', 14)
xlabel('vehicle speed (mi/hr)', 'FontSize', 12)
ylabel('stopping distance (ft)', 'FontSize', 12)
grid on
Speed (mi/hr) 20 30 40 50 60 70
Stopping Distance (ft) 46 75 128 201 292 385
Sample Problem – Plotting
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 86/142
Intro to Technical Problem Solving with MATLAB v.786
Sample Problem Plotting
Numerical Data
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 87/142
Intro to Technical Problem Solving with MATLAB v.787
Plotting Functions Numerically
ezplot is a great tool for plotting functions, but it has severaldisadvantages:
it doesn‟t provide as much control as plot, e.g. dotted lines.
you must fill in values for any constants, e.g.
When you need more control, plot numerically with plot:d = 4;
h = linspace(1,10); % Step 1 - create vector for independent variable
V = pi*d^2/4*h; % Step 2 – compute vector for dependent variable
plot(h,V,'-r') % Step 3 - plot and label
xlabel('height (m)', 'FontSize', 12)
ylabel('Volume (m^3)', 'FontSize', 12)
title('Volume of a cylinder versus its height','FontSize', 14)
grid on
hd
V cylinder 4
2
Sample Problem – Plotting
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 88/142
Intro to Technical Problem Solving with MATLAB v.788
Sample Problem Plotting
Functions Numerically
A function G(x,y,z) of three independent variables is
defined as:
Write a function that takes no inputs or outputs but
creates a plot of G(x,y,z), subject to:0.1 < x < 4
y = 5, z = 3
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 89/142
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 90/142
Intro to Technical Problem Solving with MATLAB v.790
6-3 Overlay Plots and Subplots
Allows putting more than onerelationship directly into the sameplotting window.
Two key functions: hold and legend
For multiple dependent variableswhose data are not of the same type,e.g. acceleration, speed and distance
Key function to learn: subplot
Sample Problems – Overlay Plots
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 91/142
Intro to Technical Problem Solving with MATLAB v.791
Sample Problems Overlay Plots
and Subplots
Sample Problems – Overlay Plots
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 92/142
Intro to Technical Problem Solving with MATLAB v.792
Sample Problems Overlay Plots
and Subplots
Synopsis for Overlay Plots and
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 93/142
Intro to Technical Problem Solving with MATLAB v.793
Synopsis for Overlay Plots and
Subplots
Overlay plots are used to show a family of parameterized
results
hold on is the key MATLAB command needed to turn on
overlaysSubplots are used to display plots of different independent
variables usually from one experimental data set or from
one set of equations for a single physical system.
subplot is the key MATLAB command needed to identifythe target for a created plot.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 94/142
Arrays
Chapter 7
S f h l d
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 95/142
Intro to Technical Problem Solving with MATLAB v.795
So far we have learned…
Using MATLAB for scalar computations (Ch. 3)
Saving your work in MATLAB user-defined
functions (Ch. 4)
Debugging MATLAB functions (Ch. 4)
Using MATLAB for vector operations (Ch. 5)
Using MATLAB to make 2-D plots (Ch. 6)
Using the MATLAB Help facility to let you
extend what you know (Ch. 6)
Th P
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 96/142
Intro to Technical Problem Solving with MATLAB v.796
The Pattern…
Scalars – numbers
MatLab Vectors – Ordered, linear groupings
of scalarsSimple extension – MatLab Arrays
Instead of having a one-dimensional grouping
of scalars as in vectors, MATLAB arrays aretwo-dimensional groups of scalars.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 97/142
Intro to Technical Problem Solving with MATLAB v.797
7-1 Array Creation
C i A
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 98/142
Intro to Technical Problem Solving with MATLAB v.798
Creating Arrays
A semicolon as punctuation in the square bracketoperator tells MATLAB to start a new row>> A = [1, 2, 3; 10, 20, 30]
linspace and the colon operator can be used tocreate vectors that are subsequently composed intoan array:>> A = [1:3:15; linspace(0,1,5)]
or… >> A = [(1:3:15)', linspace(0,1,5)']
Thi k
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 99/142
Intro to Technical Problem Solving with MATLAB v.799
Things to know…
A typical mistake – trying to concatenate incompatiblevectors:>> B1 = [1, 2, 3];
>> B2 = [10, 11];
>> stackedUpDown = [B1; B2]
??? Error using ==> vertcat
All rows in the bracketed expression must have
the same number of columns.
Creating an array whose elements are all value 0 (or 1) :>> twoByFourZeros = zeros(2,4)
S i f C i A
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 100/142
Intro to Technical Problem Solving with MATLAB v.7100
Synopsis for Creating Arrays
Semicolon punctuation inside the square bracket operator
indicates to MATLAB that a new row is to be created.
When concatenating arrays, their dimensions must be
consistent.
ones and zeros are built-in functions that create arrays
whose elements are all value 1 or all value 0, respectively.
ones and zeros take two arguments: the number of rowsand the number of columns in the array that will be
created.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 101/142
Intro to Technical Problem Solving with MATLAB v.7101
7-2 Accessing Array Elements
F t hi El t
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 102/142
Intro to Technical Problem Solving with MATLAB v.7102
Fetching Elements
Create an array A by the following:>> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]
Pull out the value of the element at the second row, third column:
>> x = A(2,3)
Fetch the second and third elements in the second row of A:
>> V = A(2, [2,3])
Extract the entire second column:
>> X2 = A(:, 2)
Fetch the entire third and fourth columns:
>> partOfB = A(:, [3,4])Fetch the first and second elements in the second and third columns:
>> anotherPartOfB = A([1,2], [2,3])
F t hi El t t’d
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 103/142
Intro to Technical Problem Solving with MATLAB v.7103
Fetching Elements cont’d
3547
1821
0198
6745
A
How would you address to number 0?
Row first, column next;>> A(2,4)
How about 2?>> A(3,2)
F t hi El t t’d
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 104/142
Intro to Technical Problem Solving with MATLAB v.7104
Fetching Elements cont’d
3547
1821
0198
6745
A
How can we extract the collection of numbers in the dotted box?
That is, the numbers in the 1st through 3rd rows, 2nd through 4th
columns…
Specify the row and column numbers by counting them…
A(1:3, 2:4)
S tti El t
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 105/142
Intro to Technical Problem Solving with MATLAB v.7105
Setting Elements
Create an array A by the following:
>> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]
Set the element at row two and column 4 to 100:
>> A(2,4) = 100;
Create a new array B that is identical to modified A, except that the
second and third columns are interchanged.
>> B = A;
>> B(:,[2,3]) = A(:, [3,2])
The shape of the array to be set must be the same as the shape of thearray that holds the new values.
B ilt i F ti d d i
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 106/142
Intro to Technical Problem Solving with MATLAB v.7106
Built-in Functions end and size
Create an array A by the following:
>> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]
Replace the last and next to last row/column elements with [100, 101;
200, 201]
>> A(end-1:end,end-1:end) = [100, 101; 200, 201]
For vectors, we had length to return the number of elements.
For arrays, size built-in function is used:
>> [numRows, numCols] = size(A)
S i f S tti El t
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 107/142
Intro to Technical Problem Solving with MATLAB v.7107
Synopsis for Setting Elements
Array access operations (fetch and set) are directly
analogous to vector access operations.
For array setting, the part of an array to be set and the
elements which will be inserted must be the same shape.
The colon may be used as an index element to indicate all.
end is used in array access as it is used in vector access.
To determine the number of rows and columns in an array,
use size.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 108/142
Intro to Technical Problem Solving with MATLAB v.7108
7-3 Transpose Applied to Arrays
Th T O t
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 109/142
Intro to Technical Problem Solving with MATLAB v.7109
The Transpose Operator
The transpose operator is used to flip an array.
More formally, if A is an NxM vector, then A' will be an
MxN array whose elements are defined by A'(i,j) = A(j,i).
>> D = [1,2,3,4; 10,11,12,13; 20, 21,22,23]
>> transposeD = D‟
The effect of applying the transpose operator to an array is
to flip rows and columns.
What was a row is now a column, and what was a column
is now a row.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 110/142
Intro to Technical Problem Solving with MATLAB v.7110
7-4 Array Built-in Functions,
Operators, and Expressions
Built in Functions and Operators
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 111/142
Intro to Technical Problem Solving with MATLAB v.7111
Built-in Functions and Operators
The same types in Vectors exist – with new
possibilities
>> D = [1,10; 100,110]
>> sumOverColumns = sum(D,1)
>> sumOverRows = sum(D,2)
Cell by Cell Operators
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 112/142
Intro to Technical Problem Solving with MATLAB v.7112
Cell-by-Cell Operators
Arrays A and B are defined as:>> A = [2:4; 20:10:40]
>> B = [1:3; 1:3]
Find cell-by-cell product of A and B:>> A .* B
Find A raised to the power B, cell-by-cell:>> A .^ B
Find A/B, cell-by-cell:
>> A ./ B
B
A
A
BA./B stands for , whereas B./A stands for ,cell-by-cell
Example Problem 1
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 113/142
Intro to Technical Problem Solving with MATLAB v.7113
p
Cell-by-Cell OperatorsThe ABC electronics factory makes four different items: a
48-inch HDTV, a 32-inch regular TV, a computer called
the M2 model, and a DVD player called the R2 model.
Compute:
(a) the total cost for materials used on
all four product lines for each
quarter and
(b) the total yearly cost for
materials used in each of
four product lines.
Example Problem cont’d
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 114/142
Intro to Technical Problem Solving with MATLAB v.7114
Example Problem cont d
Find by hand quarter 1 to material costs from
the HDTV product line.
532 * $892 = $474,544.
Think through the problem statement.
This problem is not conceptually difficult but is
tedious.
MATLAB provides a better way…
Matrix Operators
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 115/142
Intro to Technical Problem Solving with MATLAB v.7115
Matrix Operators
Matrix multiplication operation is defined as:
1. The number of columns in A must be equal to thenumber of rows in B. Otherwise, this is not a legal
operation.
2. Assuming Rule 1 is met the number of rows in C will be
equal to the number of rows in A.3. Likewise, the number of columns in C will be equal to
the number of columns in B.
Matrix Multiplication
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 116/142
Intro to Technical Problem Solving with MATLAB v.7116
(2,1) (2,2)
(1,1) (1,2)
Matrix Multiplication
1 2
3 4
9 7
8 6
2 X 2 2 X 2
=X
2 X 2
=
1*9 + 2*8
3*9 + 4*8
1*7 + 2*6
3*7 + 4*6
25 1959 45
Example Problem 2
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 117/142
Intro to Technical Problem Solving with MATLAB v.7117
Matrix Operators
67
89
35
61
42
,
B A
where
B A find
Revisiting Example Problem 1
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 118/142
Intro to Technical Problem Solving with MATLAB v.7118
Revisiting Example Problem 1
The ABC electronics factory makes four different items: a
48-inch HDTV, a 32-inch regular TV, a computer called
the M2 model, and a DVD player called the R2 model.
Compute:
(a) the total cost for materials used on
all four product lines for each
quarter and
(b) the total yearly cost for
materials used in each of
four product lines.
Example Problem cont’d
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 119/142
Intro to Technical Problem Solving with MATLAB v.7119
Example Problem cont d
=?
Example Problem 3
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 120/142
Intro to Technical Problem Solving with MATLAB v.7120
Matrix Operators
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 121/142
Matrix Left Division cont’d
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 122/142
Intro to Technical Problem Solving with MATLAB v.7122
Matrix Left Division cont d
Can be solved for x as follows:
Or in MatLab by left division:
y x A
y A x 1
y A x
\
Example Problem 4
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 123/142
Intro to Technical Problem Solving with MATLAB v.7123
Matrix Left Division
Jeanie, Juan, and Alexander each have some fruit. Each has anumber of apples, oranges, and pears.
All apples have the same weight, all oranges have the sameweight, and all pears have the same weight.
Jeanie has 3 apples, 2 oranges, and 1 pear. The total weight of fruit that Jeanie has is 52 ounces.
Juan has 2 apples, 3 oranges, and 1 pear. The total weight of fruit that Juan has is 50 ounces.
Alexander has 1 apple, 2 oranges, and 3 pears. The total
weight of fruit that Alexander has is 56 ounces.
What is the weight of each apple, orange, and pear?
Example Problem 5
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 124/142
Intro to Technical Problem Solving with MATLAB v.7124
Relational and Logical Operators
1. Using the find function, find and display:a. the row and column numbers of elements in A that are less than
zero
b. elements that are less than zero
c. elements that are greater than -4 but less than 4
2. Using the all or any functions, determine:
a. if all elements in A are greater than -8
b. if any elements in A are less than -5
Synopsis
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 125/142
Intro to Technical Problem Solving with MATLAB v.7125
Synopsis
Arrays are indexed by giving the row and column locations.
All cell-by-cell operations are generalizations of the corresponding
vector operation.
Matrix multiplication can be very advantageous when the problem you
are solving involves a sum of scalar multiplication operations.Matrix left division is often used to solve systems of linear
simultaneous equations.
Values in an array that meet some relational test may be extracted
using find as an indexing term.
Two output values are returned when the find function is applied to an
array: a vector of row index values and a corresponding vector of
column index values.
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 126/142
Conditional and Iterative
ProgrammingChapter 7
8-1 Program Flow
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 127/142
Intro to Technical Problem Solving with MATLAB v.7127
8 1 Program Flow
1. Straight Line Code
One line of code after
another… just in
sequence. Also called
“sequential code”.
Program Flow cont’d
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 128/142
Intro to Technical Problem Solving with MATLAB v.7128
Program Flow cont d
2. Conditional Code
Based on a test,
perform one alternative
set of code and notanother…
testYESNO
Program Flow cont’d
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 129/142
Intro to Technical Problem Solving with MATLAB v.7129
Program Flow cont d
3. Iterative code
Execute the same
block of codeagain and again …
repeat…
Synopsis for Program Flow
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 130/142
Intro to Technical Problem Solving with MATLAB v.7130
Types
There are three major types of program control: straightline control, conditional control, and iterative control.
Programming constructs for conditional control anditerative control should be considered “modules,” meaning
there is one point of entrance into the construct and onepoint of exit.
Straight line code executes in the order it is written in aprogram.
Conditional code executes one alternative of a number of
possibilities, selecting the alternative to run based on arelational/logical test of program variables.
Iterative code executes the same block of code a number of times.
8-2 Iterative Program Flow:
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 131/142
Intro to Technical Problem Solving with MATLAB v.7131
FOR
General form:
A FOR loop must end with a line containing
end.
Questions for the Iterative Case
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 132/142
Intro to Technical Problem Solving with MATLAB v.7132
Questions for the Iterative Case
How many times does
it repeat?
What controls how
many times it repeats?
How are you going to
set parameter values in
a handy way for each“pass”
repeat…repeat…
Iteration over Elements of a
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 133/142
Intro to Technical Problem Solving with MATLAB v.7133
Code to be repeated
Values taken on by changing var
Name of var that changes
f
Row Vector mySum = 0;
for itemThisTime = [1 0 -5 78]
mySum = mySum + itemThisTime;
display(itemThisTime);
display(mySum );
disp('====')
end
disp('***********************')
mySum
Iteration over Columns of an
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 134/142
Intro to Technical Problem Solving with MATLAB v.7134
Code to be repeated
Values taken on by changing var
Name of var that changes
f
ArraysumColumnProducts = 0;
for oneCol = [1 0 -5 78; 61 9 44 10]
sumColumnProducts = sumColumnProducts +
oneCol(1)*oneCol(2);display(oneCol);
display(sumColumnProducts);
disp('====')
end
disp('***********************')
sumColumnProducts
Nested FOR Loops
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 135/142
Intro to Technical Problem Solving with MATLAB v.7135
Nested FOR Loops
function cellSum = prob8_A_11(A,B)% Calculates cell-by-cell sum of two arrays
% Input: 2 arrays of dimensions nxm
% Output: Cell-by-cell product array nxm
[nRows,nCols] = size(A);
cellSum = zeros(nRows, nCols);
for i=1:nRows
for j=1:nCols
cellSum(i,j)=A(i,j)+B(i,j);
end
end
Synopsis for FOR
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 136/142
Intro to Technical Problem Solving with MATLAB v.7136
Synopsis for FOR
FOR loops are used in cases where you need more controlover computations than allowed in cell-by-cell operations.
FOR loops start with a code line that begins with keyword
for and end with keyword end.FOR loops iterate over a code block body using successivevalues of supplied vector or array.
If a FOR loop is supplied with an array, then successivevalues of the columns of the array are set to the value of
the loop variable.To understand a FOR loop, a good strategy is to “stepthrough” the loop.
8-4 Conditional Program Flow
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 137/142
Intro to Technical Problem Solving with MATLAB v.7137
8 4 Conditional Program Flow
Form 1: IFif <conditions>
<statements>
end;
J&T Computers is planning to give a
$3,000 holiday bonus to everyemployee provided ALL
employees have a performance
evaluation higher than 3/5.
For the dataset, find if bonus will begiven.
Employee Numbers,
Performance Ratings, Salaries
Conditional Program Flow
’d
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 138/142
Intro to Technical Problem Solving with MATLAB v.7138
cont’d
Form 2: IF/ELSE
if <conditions>
<statements> else
<statements>
end;
Instead of giving bonus to allemployees, consider the following
scenario:
every employee with a
performance rating of 4 or 5 gets a 5percent holiday bonus while all
other employees will get a 2
percent bonus.Employee Numbers,
Performance Ratings, Salaries
Conditional Program Flow
’d
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 139/142
Intro to Technical Problem Solving with MATLAB v.7139
cont’d
Form 3: IF/ELSEIF
if <conditions>
<statements> elseif
<statements>
end;
New scenario:Employees with performance
ratings of 5 get a 4% bonus, those
with performance ratings of 4 get
a2% bonus, and those with
performance ratings of 3 get a 1%
bonus.Employee Numbers,
Performance Ratings, Salaries
Conditional Program Flow
’d if <conditions>
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 140/142
Intro to Technical Problem Solving with MATLAB v.7140
cont’d
Form 4:
IF/ELSEIF/ELSE
if <conditions>
<statements>
elseif<statements>
else
<statements>
end;
One last scenario:employees with performance ratings
of 5 get a 4% bonus, those with
performance ratings of 4 get a 3%
bonus, those with performanceratings of 3 get a 2% bonus, and
everyone else gets a 1% bonus Employee Numbers,
Performance Ratings, Salaries
S l P bl
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 141/142
Intro to Technical Problem Solving with MATLAB v.7141
Sample Problem
I will be depositing $5,000 in the beginning
of every year in my bank account. The
bank offers an interest rate of 4%.
When will I be a millionaire?
How much savings will I have after 10 years?
Synopsis
8/4/2019 Intro Tech Matlab
http://slidepdf.com/reader/full/intro-tech-matlab 142/142
y pIF-THEN-ELSE can be used to express conditional
program control. It is best understood in four distinctforms.1. IF: In this form, one relational/logical test exists. During
execution, if the test results in true, then the commands in thefollowing block are run. If the test results in false, then thecommands are not run.
2. IF-ELSE: This form performs a relational/logical test and, if true,then runs a set of commands. If false, an alternative set of commands is run.
3. IF-ELSEIF: There can be multiple ELSEIF clauses. Only one (atmost) code block following a test will be run, which will be theone following the first test that results in true.
4. IF-ELSEIF-ELSE: This form is a combination of the second andthird forms.
The key to effective use is to correctly match the problem