Lecture 14: M/O/F/ for Engineering Applications - Part 2 BJ Furman 28NOV2011.

Slides:



Advertisements
Similar presentations
Introduction to Matlab
Advertisements

1 EMT 101 – Engineering Programming Dr. Farzad Ismail School of Aerospace Engineering Universiti Sains Malaysia Nibong Tebal Pulau Pinang Week 10.
Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
Arrays Revisited Selim Aksoy Bilkent University Department of Computer Engineering
Lecture 4 Sept 8 Complete Chapter 3 exercises Chapter 4.
Lecture 2 MATLAB fundamentals Variables, Naming Rules, Arrays (numbers, scalars, vectors, matrices), Arithmetical Operations, Defining and manipulating.
Pam Perlich Urban Planning 5/6020
Matrix Mathematics in MATLAB and Excel
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Matlab intro The Environment
MATLAB Fundamentals.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
Lecture 13: M/O/F/ for Engineering Applications - Part 1 BJ Furman 26NOV2012.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
Chapter 10 Review: Matrix Algebra
Creating scalars, vectors, matrices Ex1 & 2. Dot Product & Cross Product Ex3. Plotting Graphs Ex4. Conversion Table Ex5. Plotting functions Finishing Ex4.
MATLAB Basics With a brief review of linear algebra by Lanyi Xu modified by D.G.E. Robertson.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
MATLAB Tutorials Session I Introduction to MATLAB Rajeev Madazhy Dept of Mechanical Engineering LSU.
1 Week 3: Vectors and Matrices (Part III) READING: 2.2 – 2.4 EECS Introduction to Computing for the Physical Sciences.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
CSE123 Lecture 5 Arrays and Array Operations. Definitions Scalars: Variables that represent single numbers. Note that complex numbers are also scalars,
Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
INTRODUCTION TO MATLAB LAB# 01
Numerical Computation Lecture 2: Introduction to Matlab Programming United International College.
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
Introduction to Matlab Module #2 Page 1 Introduction to Matlab Module #2 – Arrays Topics 1.Numeric arrays (creation, addressing, sizes) 2.Element-by-Element.
Matlab for Engineers Manipulating Matlab Matrices Chapter 4.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
MAE 1202: AEROSPACE PRACTICUM An Introduction to MATLAB: Part 2 Mechanical and Aerospace Engineering Department Florida Institute of Technology Developed.
MATLAB Environment ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
Recap Sum and Product Functions Matrix Size Function Variance and Standard Deviation Random Numbers Complex Numbers.
Lecture 2 - Matlab Introduction CVEN 302 June 5, 2002.
Scientific Computing Introduction to Matlab Programming.
ES 240: Scientific and Engineering Computation. Chapter 2 Chapter 2: MATLAB Fundamentals Uchechukwu Ofoegbu Temple University.
Working with Arrays in MATLAB
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
A string is an array of characters Strings have many uses in MATLAB Display text output Specify formatting for plots Input arguments for some functions.
Lecture 3: M/O/F/ for Engineering Applications B Burlingame 16September2015.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
Part 1 Chapter 2 MATLAB Fundamentals PowerPoints organized by Dr. Michael R. Gustafson II, Duke University and Prof. Steve Chapra, Tufts University All.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
(The Transpose Operator) 1 >> C=[ ; ; ] C = >> D=C' D =
Array Creation ENGR 1181 MATLAB 2. Civil engineers store seismic data in arrays to analyze plate tectonics as well as fault patterns. These sets of data.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Array Operations ENGR 1181 MATLAB 4.
Array Creation ENGR 1187 MATLAB 2. Today’s Topics  Arrays: What are they?  Vectors  Matrices  Creating Arrays.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
1 Lecture 5 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
September 15, 2005 Lecture 5 - By Paul Lin 1 CPET 190 Lecture 5 Problem Solving with MATLAB
1 Lecture 3 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
CMPS 1371 Introduction to Computing for Engineers VECTORS.
1 Faculty Name Prof. A. A. Saati. 2 MATLAB Fundamentals 3 1.Reading home works ( Applied Numerical Methods )  CHAPTER 2: MATLAB Fundamentals (p.24)
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Manipulating MATLAB Vector, Matrices 1. Variables and Arrays What are variables? You name the variables (as the programmer) and assign them numerical.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
Lecture 12: M/O/F/ for Engineering Applications B Burlingame 27 April 2016.
An Introduction to Programming in Matlab Emily Blumenthal
To add, subtract, multiply, and divide, absolutely follow the mathematical rules. 1. All the rules 2. The element-per-element operator 3. Ex1: graphing.
LAB 2 Vectors and Matrices Dr.Abdel Fattah FARES.
Use of Mathematics using Technology (Maltlab)
Presentation transcript:

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 (single row or single column of data elements) Matrix :  A two-dimensional array (more than one row and/or column of data elements) >> A=[1:9] >> B=[1:9]’ >> C=[1:3; 4:6; 7:9] row or column? C = column vector

Colon Operator vs. linspace() What will the following do?  D=0 : 3 : 10  F=linspace(0, 10, 11) 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 base : increment : limit start : end : n

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; ], 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?  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  Reshape L = reshape(I(9:-1:1),3,3) I = I’

Matrix and Array Arithmetic Arithmetic operators: ++ - * / \ ^ ’ a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 sscalar  (matrix or array) --> ? ((matrix or array)  (matrix or array) --> ? ((matrix or arrays) must be of the same size FFor the other operators, need to distinguish between matrix and array operation Matrix arithmetic operations pper rules of linear algebra rows and columns must conform For example, A x B: must have column and row agreement Array arithmetic operations eelement-by-element Denote with dot operator:.*./.\.^.’ (array transpose) add.sub.mult.right div.left div.expon.algebr. transpose A B

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 --> ? L * O --> ? L* O’ --> ? ??? Error using ==> + Matrix dimensions must agree. ??? Error using ==> * Inner matrix dimensions must agree. 15 Same as sum(L.* O) (1x5 * 1x5 does not work!) (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 Matrix operations  Matrix division Recall the circuit analysis  R1=10k  R2=R3=5k  V=10V Matrix solution R2 R1 R3 +V i1 i2 i3 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 Think of it like inverting R and multiplying on the left side of V

Circuit Analysis Solution Circuit analysis solution:  Build R, build V, solve for i  Build R all at once  R=[1 -1 1; e3; 0 10e3 0] or build by rows and combine  eq1 = [ ]  eq2 = [0 0 10e3]  eq3 = [0 10e3 0]  R = [eq1; eq2; eq3]  Build V V = [ ]’ (note: transposed)  Solve I = R \ V I = R \ V R1=10k R2=R3=5k V=10V

Dot Product Example Another example of element-by-element operations dot product of two vectors

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

Dot Product Function in M/O/F Write the function Test it out 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); A = [ ]; B = [ ];% 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, rms.m

Root Mean-Square Function Development Functions, cont.  Example: root-mean- square function, cont. Pseudocode:  square each element of x  sum the squares  divide by N  take the square root Square each element  xs = x.^2 Sum the squares  sums = sum(xs) Divide by N  N = length(x)  ms = sums/N Take the square root  rms = sqrt(ms) Before you write the function, make sure the name you propose is not already used!  Use: which name to check

Root Mean-Square Function Implementation Functions, cont.  Example: root-mean-square function, cont. function [y] = rms(v) % RMS(v) root mean square of the elements of the column vector v % Function rms(v) returns the root mean square of the elements % of the column vector, v 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? H1 comment line (used in lookfor) Comments that will be displayed by help command

More Robust Root Mean-Square Function Functions, cont.  Make rms function more robust to work with row or column vector or matrix with column vectors of data function [rmsout] = rms2(v) %RMS2(v) Root mean square of v % Function rms2(v) returns a row vector, where % each element is the rms value of values in each % column of v vs = v.^2; s = size(v); rmsout = sqrt(sum(vs,1)/s(1));

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'); Adapted from: visited 15NOV2009http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html file_io_example.m

More on Plotting Add a red line through the data Plot multiple sets of data on a single graph and add a legend grid on Sub-plots  Format: subplot (m,n,p) Figure window divided into m x n matrix of plotting areas Procedure:  Pick the sub-plot window  Execute plot commands for that sub-plot % plot precip vs. month with circles plot(month,precip,'o',month,precip,'-r'); General Format: plot (x, y, fmt,...) % copy first column of PDXtemperature into month month = PDXtemperature(:,1); % and second column into high_temp high_temp = PDXtemperature(:,2); % and third column into low temp low_temp = PDXtemperature(:,3); % and fourth column into avg temp avg = PDXtemperature(:,4); % generate the plot plot(month,high_temp,'ko',month,low_temp,'k+',month,avg,‘r-'); % add axis labels and plot title xlabel('Month'); ylabel('temperature (degrees F)'); title('Monthly average temperature for PDX'); % add a plot legend using labels read from the file legend('High','Low','Avg'); multi_plot.m

Vector Dot Product Example X Y Find the X and Y components of the vector, V ivv x ˆ   Back

Review

References Matlab. (2009, November 6). In Wikipedia, the free encyclopedia. Retrieved November 6, 2009, from  Matlab tutorials: GNU Octave. (2009, October 31). In Wikipedia, the free encyclopedia. Retrieved November 6, 2009, from  Octave main page: ( access to pre-built installers)  Octave tutorials: FreeMat. ftp:// ses/ENGR-25.htm ftp:// ses/ENGR-25.htm