Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Lecture 14 Matlab Octave FreeMat pt2

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Lecture 14 Matlab Octave FreeMat pt2

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 28

Lecture 14: M/O/F/ for

Engineering Applications -
Part 2

BJ Furman
28NOV2011
The Plan for Today
 Matlab/Octave/FreeMat (M/O/F) for
engineering applications – part 2
 Recap M/O/F key concepts
 Element-by-element operations (dot operator)
 Function examples
 2D graphs
 File IO
 Resources for more information
Learning Objectives
 Distinguish between matrix and array
arithmetic, and use them appropriately
 Explain the differences between script
files and functions
 Explain the basic elements of creating a
2D graph
 Explain how to read from and write to
files
Last Lecture
 Overview of Matlab/Octave
 Useful commands
 The array as a fundamental element
 creating arrays
 indexing elements
 vectors
 colon operator
 linspace
 logspace
 extracting sub-arrays using indexing and the colon operator
 special matrices
 ones(), zeros(), diag(), eye()
 Introduction to plotting in M/O/F via script file
 comparison to Ch and Excel
Arrays, Vectors, and Matrices
 Array :
 A collection of data elements
arranged in rows and columns
 Vector:
 A one-dimensional array >> A=[1:9] row or column?
(single row or single column
of data elements) >> B=[1:9]’ column vector

 Matrix :
 A two-dimensional array >> C=[1:3; 4:6; 7:9]
(more than one row and/or
C=
column of data elements) 1 2 3
4 5 6
7 8 9
Colon Operator vs. linspace()
 What will the following do?
 D=0 : 3 : 10 base : increment : limit
 F=linspace(0, 10, 11) start : end : n
 Observations about the two methods:
 both methods produce vectors with equally spaced
elements
 colon operator method allows you to specify the first
element and the interval spacing between elements,
but not the number of elements
 If just start : end, then spacing is 1
 linspace method allows you to specify the first and
last elements of the vector, but not the spacing
between elements
Review of length() and size()
 What will the following do?
 length(ones(1,3))
 length returns the number of elements of the vector
 size(zeros(2,3))
 size returns the size of the dimensions of its
argument
Review of Array Manipulation
 Given G=[2 4 6; 8 10 12], what is:
 G(2,3)
 G(: , 2)

 G(4)

 G(1,1)=0

 G(1, :)=0

 Observations:
 Array indexing begins with 1 (contrast with C)
 : means “all of” the elements in that dimension
 Extract elements by indexing
 Extract sub-arrays using vectors as the indexing
arguments
More Array Manipulation
 Suppose H=1:9 (what will this produce?)
 How could we form into a 3x3 matrix?
 Reshape function
 I=reshape(H,3,3)
 How to transpose the rows to be the columns? I = I’
 Reverse the order of the rows of I
 J=I(3:-1:1,:)
 Reverse the order of the columns of I (how?)
 K=I(:, 3:-1:1)
 Reverse the order of all the elements of I (how?)
 Pseudocode:
 Index I in reverse order
L = reshape(I(9:-1:1),3,3)
 Reshape
Matrix and Array Arithmetic
 Arithmetic operators:
 + - * / \ ^ ’
add. sub. mult. right div. left div. expon. algebr. transpose
 addition and subtraction are done element-by-element (same for
matrix and array arithmetic)
 Unless one is a scalar, the operands must be of the same size
 scalar  (matrix or array) --> ?
 (matrix or array)  (matrix or array) --> ?
 (matrix or arrays) must be of the same size
For the other operators, need to distinguish between matrix and array

operation
n columns B

 
 Matrix arithmetic operations
 mn 
 per rules of linear algebra
 rows and columns must conform A n rows n  p
 For example, A x B: must have column and row agreement
 Array arithmetic operations
 element-by-element
 Denote with dot operator: .* ./ .\ .^ .’ (array transpose)
Matrix and Array Arithmetic Examples
 Scalar and matrix operands
 If L=ones(1,5) and M=ones(1,4)
 N = 2*L --> ?
 N–1 --> ?
 Non-scalar operations
 If O = [ 1:5 ]
 O + M --> ? ??? Error using ==> +
Matrix dimensions must agree.
??? Error using ==> * (1x5 * 1x5 does not work!)
 L * O --> ? Inner matrix dimensions must agree.

 L* O’ --> ? 15 Same as sum(L .* O)


(1x5 * 5x1 works! Inner matrix dimensions agree. Results in a 1x1)
Array Operations
 Element-by-element array operation
 Ex: Given a set of distances and times, calculate
average speeds and maximum of averages
 How would you do this in C?
 Pseudocode:
 Calculate avg. speeds: speed[i] = distance[i] / time[i], for i=1 to 4
 Determine maximum speed
 M/O/F (vectorize!):
 distances=[120, 213, 87, 35] (in miles)
 times=[ 2, 3.8, 0.9, 0.6] (in hours)
 speeds=distances ./ times %( note: ‘dot /’  divide element-by-element)
 max_speed=max(speeds)
 To get the maximum speed and its index:
 [max_speed, i] = max(speeds)
Circuit Analysis Equations i2
i1
R2
i1  i2  i3  0
 Matrix operations +V 0i1  0i2  i3 R1  V

R3
i3

R1
 Matrix division 0i1  R2  R3 i2  0i3  V
 Recall the circuit analysis
 R1=10k
1 1  1  i1   0 
 R2=R3=5k 0 0 R1  i2   V 
 V=10V     
 Matrix solution 0 R2  R3  0  i3  V 

1
Ri  V R 1Ri  R 1V  i  R V R i V
use ' left' division to solve for i
iR\V Think of it like inverting R and multiplying on the left side of V
If we had iR = V instead, we’d use ‘right’ division to solve for i: ( i = R / V )
Think of it like inverting R and multiplying on the right side of V: i = VR-1
Circuit Analysis Solution
 Circuit analysis solution: •R1=10k
 Build R, build V, solve for i •R2=R3=5k
 Build R •V=10V
 all at once 1  1  i1   0 
1
 R=[1 -1 1; 0 0 10e3; 0 10e3 0] 0
or 0 R1  i2   V 
    
 build by rows and combine 0 R2  R3  0  i3  V 
 eq1 = [ 1 -1 1]


eq2 = [0 0 10e3]
eq3 = [0 10e3 0]
R i V
 R = [eq1; eq2; eq3]
 Build V
 V = [0 10 10]’ (note: transposed)
 Solve I = R \ V
 I=R\V
Dot Product Example
 Another example of element-by-element
operations 
v1    
 dot product of two vectors   v1  v2  v1 v2 cos( )
v2
 
v1  3iˆ  2 ˆj  5kˆ v2  2iˆ  4 ˆj  10kˆ

iˆ, ˆj , kˆ are unit vectors for a cartesian coordinate system


their coefficients are called ' measure numbers'
 
what is v1  v2?
 
v1  v2  (3)(2)  (2)(4)  (5)(10)  6  8  50  52
Dot Product Function Development
 Define the problem
 Create a function that will take two vectors as arguments and
will return their vector dot product
 Inputs
 v1, v2 (three-element row vectors)
 Outputs
 z (the dot product)
 Algorithm
 Multiply v1 and v2 element-by-element
 Sum the element-by-element products
 Return the sum Try it in Matlab/Octave :
v1  [3 2  5] v 2  [2  4 10]
sum(v1 . * v 2)
Dot Product Function in M/O/F
 Write the function
function [z] = dot_prod(v1, v2)
% dot_prod(v1,v2) computes the vector dot product between vectors v1 and v2
% Function dot_prod(v1,v2) computes and returns the vector dot product between
vectors v1 and v2

z = sum(v1.*v2);

 Test it out
A = [ 1 2 3 ];
B = [ 4 5 6 ]; % what should A dot B result in?

A_dot_B = dot_prod(A,B)
Review of Functions
 Functions
 Like script M-files, but several differences:
 first line (function declaration) must be of the form:
function [output args] = function_name(input args)
 variables generated in the function are local to the
function, whereas for script files, variables are global
 must be named, ‘function_name.m’ (same as file name)
 Make sure you add comments at the start that
describe what the function does (see example code)
 Example: root-mean-square function, N
rms.m x2
i
Given, x  [ x1 , x2 ,..., x N ] RMS  i 1
N
Root Mean-Square Function Development
 Functions, cont. N
 Example: root-mean-
square function, cont.

i 1
xi2
Given, x  [ x1 , x2 ,..., x N ] RMS 
 Pseudocode: N
 square each element of
x
 sum the squares  Take the square root
 divide by N
 take the square root
 rms = sqrt(ms)
 Square each element  Before you write the
 xs = x .^2 function, make sure the
 Sum the squares name you propose is
 sums = sum(xs) not already used!
 Divide by N  Use: which name
 N = length(x)
to check
 ms = sums/N
Root Mean-Square Function Implementation

 Functions, cont.
 Example: root-mean-square
function, cont.
function [y] = rms(v)
H1 comment line
% RMS(v) root mean square of the elements of the column vector v
(used in lookfor) % Function rms(v) returns the root mean square of the elements
Comments that % of the column vector, v
will be displayed
by help command
vs = v.^2; % what does this line do? Also note semicolon.
s = length(v);
y = sqrt(sum(vs)/s);

Let v=sin([0: 0.01*pi: 2*pi]’), one period of a sine wave. The RMS value
of a sine wave is its amplitude*1/sqrt(2)

Does rms() work with a row vector? How about a matrix?


More Robust Root Mean-Square Function

 Functions,
function [rmsout] = rms2(v)
cont. %RMS2(v) Root mean square of v
% Function rms2(v) returns a row vector, where
 Make rms % each element is the rms value of values in each
function more % column of v

robust vs = v.^2;
s = size(v);
 to work with rmsout = sqrt(sum(vs,1)/s(1));
row or column
vector or
matrix with
column vectors
of data
File I/O with M/O/F
 Data Input - simplest method
 load command
 Ex: load(‘data_file.txt’)
 reads on a row-by-row basis

 data values separated by spaces or commas and

rows terminated by new line


 columns must have the same number of elements

 data is stored in workspace in an array with same

name as the argument used in the load function


 Ex. Portland International Airport monthly rainfall

 load (‘PDXprecip.dat’) % must be in search path!


File I/O with M/O/F, cont.
 Data Output - simplest method
 Save command
 Ex: save(‘data_file_name’)
 Saves all the variables into a .mat file named
‘data_file_name’
 Many other commands are available for special
purpose file I/O
File I/O and Plotting Example
% read data into PDXprecip matrix
load('PDXprecip.dat');

% copy first column of PDXprecip into month


month = PDXprecip(:,1);

% and second column into precip


precip = PDXprecip(:,2);

% plot precip vs. month with circles


plot(month,precip,'o');

% add axis labels and plot title


xlabel('month of the year');
ylabel('mean precipitation (inches)');
title('Mean monthly precipitation at Portland International Airport');
file_io_example.m
Adapted from: http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html
visited 15NOV2009
More on Plotting General Format:
plot (x, y, fmt, ...)

 Add a red line through the


% plot precip vs. month with circles
data
plot(month,precip,'o',month,precip,'-r');
 Plot multiple sets of data
on a single graph and add % copy first column of PDXtemperature into month
month = PDXtemperature(:,1);
a legend
% and second column into high_temp
 grid on high_temp = PDXtemperature(:,2);
 Sub-plots % and third column into low temp
 Format: low_temp = PDXtemperature(:,3);

 subplot (m,n,p) % and fourth column into avg temp


 Figure window divided avg = PDXtemperature(:,4);
into m x n matrix of % generate the plot
plotting areas plot(month,high_temp,'ko',month,low_temp,'k+',month,avg,‘r-');
 Procedure:
% add axis labels and plot title
 Pick the sub-plot xlabel('Month');
window ylabel('temperature (degrees F)');
 Execute plot title('Monthly average temperature for PDX');
commands for that
sub-plot % add a plot legend using labels read from the file
legend('High','Low','Avg');

multi_plot.m
Vector Dot Product Example
Find the X and Y components of the vector, V
    
that is, find v x and v y , so that v x  v y  v

Y  v 
vy
v 

ĵ vx

iˆ X

    ˆ  v iˆ cos( )  v (1) cos( )  v cos( )


vx v i x x x

    
v y  v  ˆj  v y ˆj cos(90   )  v y (1) cos(90   )  v y sin( )

Back
Review
References
 Matlab. (2009, November 6). In Wikipedia, the free encyclopedia.
Retrieved November 6, 2009, from
http://en.wikipedia.org/wiki/Matlab
 Matlab tutorials:
http://www.mathworks.com/academia/student_center/tutorials/launchpad.html
 GNU Octave. (2009, October 31). In Wikipedia, the free
encyclopedia. Retrieved November 6, 2009, from
http://en.wikipedia.org/wiki/GNU_Octave
 Octave main page: http://www.gnu.org/software/octave/
(http://octave.sourceforge.net/ access to pre-built installers)
 Octave tutorials: http://homepages.nyu.edu/~kpl2/dsts6/octaveTutorial.html,
http://smilodon.berkeley.edu/octavetut.pdf
 FreeMat. http://freemat.sourceforge.net/index.html
 ftp://www.chabotcollege.edu/faculty/bmayer/
ChabotEngineeringCourses/ENGR-25.htm

You might also like