MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

Similar documents
MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB

MAT 343 Laboratory 2 Solving systems in MATLAB and simple programming

MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB

FreeMat Tutorial. 3x + 4y 2z = 5 2x 5y + z = 8 x x + 3y = -1 xx

TUTORIAL 1 Introduction to Matrix Calculation using MATLAB TUTORIAL 1 INTRODUCTION TO MATRIX CALCULATION USING MATLAB

LAB 2: Linear Equations and Matrix Algebra. Preliminaries

Numerical Methods Lecture 1

Dr Richard Greenaway

x = 12 x = 12 1x = 16

Teaching Manual Math 2131

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Physics 326G Winter Class 2. In this class you will learn how to define and work with arrays or vectors.

Introduction to Matlab

Introduction to Matlab. By: Hossein Hamooni Fall 2014

7 Control Structures, Logical Statements

Introduction to MATLAB

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

1 Overview of the standard Matlab syntax

Dynamics and Vibrations Mupad tutorial

Getting To Know Matlab

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

AMS 27L LAB #2 Winter 2009

Vector: A series of scalars contained in a column or row. Dimensions: How many rows and columns a vector or matrix has.

Introduction to MATLAB

MATLAB = MATrix LABoratory. Interactive system. Basic data element is an array that does not require dimensioning.

Dr Richard Greenaway

Matrix Inverse 2 ( 2) 1 = 2 1 2

1 Introduction to Matlab

MBI REU Matlab Tutorial

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

Introduction to Matlab

ECON 502 INTRODUCTION TO MATLAB Nov 9, 2007 TA: Murat Koyuncu

Lecture 2. Arrays. 1 Introduction

Computational Photonics, Summer Term 2012, Abbe School of Photonics, FSU Jena, Prof. Thomas Pertsch

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Lecturer: Keyvan Dehmamy

MATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano

AN INTRODUCTION TO MATLAB

Introduction to MATLAB for Engineers, Third Edition

CME 192: Introduction to Matlab

Mathematics 4330/5344 #1 Matlab and Numerical Approximation

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

Matrices. A Matrix (This one has 2 Rows and 3 Columns) To add two matrices: add the numbers in the matching positions:

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

What is MATLAB and howtostart it up?

Laboratory 1 Octave Tutorial

BEGINNING MATLAB. R.K. Beatson Mathematics Department University of Canterbury. 2 Matlab as a simple matrix calculator 2

Introduction to Matlab

Matlab and Octave: Quick Introduction and Examples 1 Basics

Matlab- Command Window Operations, Scalars and Arrays

LAB 2 VECTORS AND MATRICES

Repetition Structures Chapter 9

Octave Tutorial Machine Learning WS 12/13 Umer Khan Information Systems and Machine Learning Lab (ISMLL) University of Hildesheim, Germany

Vectors and Matrices. Chapter 2. Linguaggio Programmazione Matlab-Simulink (2017/2018)

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

MATLAB Premier. Middle East Technical University Department of Mechanical Engineering ME 304 1/50

MATLAB for beginners. KiJung Yoon, 1. 1 Center for Learning and Memory, University of Texas at Austin, Austin, TX 78712, USA

Introduction to MATLAB

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

University of Alberta

Introduction to MATLAB 7 for Engineers

4. Linear Algebra. In maple, it is first necessary to call in the linear algebra package. This is done by the following maple command

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

Computational Mathematics

Summer 2009 REU: Introduction to Matlab

Finite Math - J-term Homework. Section Inverse of a Square Matrix

Computer Packet 1 Row Operations + Freemat

A Guide to Using Some Basic MATLAB Functions

SF1901 Probability Theory and Statistics: Autumn 2016 Lab 0 for TCOMK

MATLAB NOTES. Matlab designed for numerical computing. Strongly oriented towards use of arrays, one and two dimensional.

Introduction to MATLAB Programming

Section 1.8. Simplifying Expressions

Experiment 1: Introduction to MATLAB I. Introduction. 1.1 Objectives and Expectations: 1.2 What is MATLAB?

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

Introduction to MatLab. Introduction to MatLab K. Craig 1

Physics 326G Winter Class 6

MATLAB COURSE FALL 2004 SESSION 1 GETTING STARTED. Christian Daude 1

CMAT Language - Language Reference Manual COMS 4115

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

Chapter 18 out of 37 from Discrete Mathematics for Neophytes: Number Theory, Probability, Algorithms, and Other Stuff by J. M. Cargal.

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

Grace days can not be used for this assignment

Matlab Tutorial. Get familiar with MATLAB by using tutorials and demos found in MATLAB. You can click Start MATLAB Demos to start the help screen.

EN 001-4: Introduction to Computational Design. Matrices & vectors. Why do we care about vectors? What is a matrix and a vector?

Math Scientific Computing - Matlab Intro and Exercises: Spring 2003

How to learn MATLAB? Some predefined variables

2.0 MATLAB Fundamentals

Introduction to Matlab

MAT 275 Laboratory 3 Numerical Solutions by Euler and Improved Euler Methods (scalar equations)

Introduction to MATLAB

MATLAB SUMMARY FOR MATH2070/2970

Matrices 4: use of MATLAB

Getting Started with MATLAB

YOGYAKARTA STATE UNIVERSITY MATHEMATICS AND NATURAL SCIENCES FACULTY MATHEMATICS EDUCATION STUDY PROGRAM

MATLAB TUTORIAL FOR MATH/CHEG 305

A QUICK INTRODUCTION TO MATLAB

Introduction to Matlab

0_PreCNotes17 18.notebook May 16, Chapter 12

Transcription:

MATLAB sessions: Laboratory MAT 75 Laboratory Matrix Computations and Programming in MATLAB In this laboratory session we will learn how to. Create and manipulate matrices and vectors.. Write simple programs in MATLAB NOTE: For your lab write-up, follow the instructions of LAB. Matrices and Linear Algebra Matrices can be constructed in MATLAB in different ways. For example the matrix 8 6 can be entered as 4 9 or >> A=[8,,6;,5,7; 4,9,] 8 6 4 9 >> A=[8 6; ; 4 9 ] 8 6 4 9 Note how we can separate columns with commas or spaces, and separate rows with semi-colons. We can also defined the matrix as the concatenation of rows >> row=[8,,6]; row=[,5,7]; row=[4,9,]; A=[row;row;row] 8 6 4 9 or columns >> col=[8;;4]; col=[;5;9]; col=[6;7;]; A=[col,col,col] 8 6 4 9 Note the use of, and ;. Concatenated rows/columns must have the same length. Larger matrices can be created from smaller ones in the same way: >> C=[A,A] % Same as C=[A A] C = 8 6 8 6 4 9 4 9 DISTRIBUTED - c 08 Stefania Tracogna, SoMSS, ASU

MATLAB sessions: Laboratory The matrix C has dimension 6 ( by 6 ). On the other hand smaller matrices (submatrices) can be extracted from any given matrix: >> A(,) % entry of A in nd row, rd column 7 >> A(,:) % st row of A 8 6 >> A(:,) % rd column of A 6 7 >> A([,],[,]) % keep coefficients in rows & and columns & 6 9 >> A(,) % entry in last column and last row of A We can also change elements in a matrix A: >> A(,) =9 %change the element in the st row and nd column of the matrix A to 9. 8 9 6 4 9 The entries of a row or column vector can be referenced by a single index. For instance: >> v=[;-;;5] v = - 5 >> v() % third entry of the vector v Some matrices are already predefined in MATLAB: >> I=eye() % the Identity matrix I = 0 0 0 0 0 0 >> magic() 8 6 4 9 (what is magic about this matrix?) Matrices can be manipulated very easily in MATLAB (unlike Maple). Here are sample commands to exercise with: DISTRIBUTED - c 08 Stefania Tracogna, SoMSS, ASU

MATLAB sessions: Laboratory >> A=magic(); >> B=A % transpose of A, i.e, rows of B are columns of A B = 8 4 5 9 6 7 >> A+B % sum of A and B 6 4 0 4 0 6 0 6 4 >> A*B % standard linear algebra matrix multiplication 0 7 5 7 8 7 5 7 0 >> A.*B % coefficient-wise multiplication 64 4 5 6 4 6 4 One MATLAB command is especially relevant when studying the solution of linear systems of differentials equations: x=a\b determines the solution x = A b of the linear system Ax = b. Here is an example: >> A=magic(); >> z=[,,] % same as z=[;;] z = >> b=a*z b = 8 4 8 >> x = A\b % solve the system Ax = b. Compare with the exact solution, z, defined above. x = >> y =inv(a)*b % solve the system using the inverse: less efficient and accurate.0000.0000.0000 Now let s check for accuracy by evaluating the difference z x and z y. In exact arithmetic they should both be zero since x, y and z all represent the solution to the system. >> z - x % error for backslash command 0 0 DISTRIBUTED - c 08 Stefania Tracogna, SoMSS, ASU

MATLAB sessions: Laboratory 0 >> z - y % error for inverse.0e-05 * -0.444 0-0.888 Note the multiplicative factor 0 5 in the last computation. MATLAB performs all operations using standard IEEE double precision. Important!: Because of the finite precision of computer arithmetic and roundoff error, vectors or matrices that are zero (theoretically) may appear in MATLAB in exponential form such as.0e-5 M where M is a vector or matrix with entries between and. This means that each component of the answer is less than 0 5 in absolute value, so the vector or matrix can be treated as zero (numerically) in comparison to vectors or matrices that are on the order of in size. EXERCISE (a) Enter the following matrices and vectors in MATLAB 0 4 4 5 6, B = 5 6, b = 9 4 7 0 8 9 6, c =, d = [ 5 6 7 ]. (b) Perform the following operations: AB, BA, db and Ac (use standard linear algebra multiplication). (c) Construct a 4 matrix C = [ B c ] [ ] A and a 4 matrix D =. d (d) Use the backslash command to solve the system Ax = b. (e) Replace B(, ) with 0. (f) Change the second element of d to 8. (g) Extract the nd column of the matrix A and store it in the vector a. (h) A row or a column of a matrix can be deleted by assigning the empty vector [] to the row or the column. For instance A(,:)=[] deletes the second row of the matrix A. Delete the first column of the matrix B. MATLAB Programming It is often advantageous to be able to execute a segment of a code a number of times. A segment of a code that is executed repeatedly is called a loop. To understand how loops work, it is important to recognize the difference between an algebraic equality and a MATLAB assignment. Consider the following commands: >> counter = counter = >> counter = counter + counter = DISTRIBUTED - c 08 Stefania Tracogna, SoMSS, ASU 4

MATLAB sessions: Laboratory The last statement does not say that counter is one more than itself. When MATLAB encounters the second statement, it looks up the present value of counter (), evaluates the expression counter + (), and stores the result of the computation in the variable on the left, here counter. The effect of the statement is to increment the variable counter by, from to. Similarly, consider the commands: >> v=[,,] v = >> v=[v,4] v = 4 When MATLAB encounters the second statement, it looks up the present value of v, adds the number 4 as entry of the vector, and stores the result in the variable on the left, here v. The effect of the statement is to augment the vector v with the entry 4. There are two types of loops in MATLAB: for loops and while loops for loops When we know exactly how many times to execute the loop, the for loop is often a good implementation choice. One form of the command is as follows: for k=kmin:kmax The loop index or loop variable is k, and k takes on integer values from the loop s initial value, kmin, through its terminal value, kmax. For each value of k, MATLAB executes the body of the loop, which is the list of commands. Here are a few examples: Determine the sum of the squares of integers from to 0: + + +... + 0. S = 0; % initialize running sum for k = :0 S = S+k^; S Because we are not printing intermediate values of S, we display the final value of S after the loop by typing S on a line by itself. Try removing the ; inside the loop to see how S is incremented every time we go through the loop. Determine the product of the integers from to 0:... 0. p = ; % initialize running product for k = :0 p = p*k; p The counter in a for loop can be given explicit increments: for k = kmin:kstep:kmax to advance the counter k by kstep each time. For instance the following code evaluates the sum of the squares of the even integers + 4 +... + DISTRIBUTED - c 08 Stefania Tracogna, SoMSS, ASU 5

MATLAB sessions: Laboratory SE = 0; % initialize running sum for k = :: % the counter starts at, s at and has increments of SE = SE+k^; SE Note that k = kmin:kstep:kmax is also a vector. A for loop essentially iterates through each element of the vector. Also, the counter k is a variable itself. In fact, the counter doesn t have to be called k - it can be called anything. The sum and prod functions Whenever possible all these constucts should be avoided and built in MATLAB functions used instead to improve efficiency. In particular lengthy loops introduce a substantial overhead. Two examples of MATLAB built in functions are sum and prod. If x is a vector, then sum(x) sums all the elements of x. Therefore the sum function takes a vector as input and sums its elements. Hence, we can create a vector containing all the terms of the sum we wish to compute and pass that vector as input to the sum function. The value of S in the example above can be evaluated using the built-in function sum. We first create the vector 4 5 6 7 8 9 0 using the colon operator, :0, we then square the entries of this vector using (:0).^ (note the dot before the caret, which is necessary to perform componentwise operations.) This yields the vector 4 9 6 5 6 49 64 8 00. Then we compute the sum of the entries of this vector. All this can be accomplished with a single MATLAB statement: >> S = sum((:0).^) Similarly, we can compute the value of SE with a single MATLAB command: >> SE = sum((::).^) Type help sum to see how the built in sum function works. The built in prod function takes a vector as input and multiplies all its elements. So, for instance, the product of the integers from to 0:... 0 can be evaluated as >> p = prod(:0) Type help prod to see how the built in prod function works. EXERCISE Recall that a geometric sum is a sum of the form a + ar + ar + ar +.... (a) Write a function file that accepts the values of r, a and n as arguments and uses a for loop to return the sum of the first n terms of the geometric series. Test your function for a = 8, r = /4 and n = 6. (b) Write a function file that accepts the values of r, a and n as arguments and uses the built in command sum to find the sum of the first n terms of the geometric series. Test your function for a = 8, r = /4 and n = 6. Hint: Start by defining the vector e=0:n- and then evaluate the vector R = r.^e. It should be easy to figure out how to find the sum from there. EXERCISE The counter in a for or while loop can be given explicit increment: for i =m:k:n to advance the counter i by k each time. In this problem we will evaluate the product of the first 7 even numbers 4 6... 4 in two ways: DISTRIBUTED - c 08 Stefania Tracogna, SoMSS, ASU 6

MATLAB sessions: Laboratory (a) Write a script file that evaluates the product of the first 7 even numbers using a for loop. (b) Evaluate the product of the first 7 even numbers using a single MATLAB command. MATLAB command prod. Use the while loop The while loop repeats a sequence of commands as long as some condition is met. The basic structure of a while loop is the following: while <condition> Here are some examples: Determine the sum of the inverses of squares of integers from until the inverse of the integer square is less than 0 0 : + +... + k while k 0 0. S = 0; % initialize running sum k = ; % initialize current integer incr = ; % initialize test value while incr>=e-0 % check whether the condition is met S = S+incr; % add term to the sum k = k+; % update the counter incr = /k^; % evaluate the next test value What is the value of S returned by this script? Compare to k= k = π 6. Create a row vector y that contains all the factorials below 000: y = [!,!,!,... k! ] while k! < 000. y = []; % initialize the vector y to the empty vector k = ; % initialize the counter value = ; % initialize the test value to be added to the vector y while value < 000 y(k) = value; % assign k-th component of the vector y k = k+; % update the counter value = factorial(k); % evaluate the next test value y EXERCISE 4 Write a script file that creates a row vector v containing all the powers of 4 below 5000. The output vector should have the form: v = [ 4, 6, 64,... ]. Use a while loop. if statement The basic structure of an if statement is the following: if condition elseif condition DISTRIBUTED - c 08 Stefania Tracogna, SoMSS, ASU 7

MATLAB sessions: Laboratory : else Here is an example: Evaluate x +, x y = x, x > for a given (but unknown) scalar x and, if x =, display y is undefined at x =. function y=f(x) if x== disp( y is undefined at x = ) elseif x <= y=x^+; else y=/(x-); We can test the file by evaluating it at different values of x. Below we evaluate the function at x =, x = and x = 4. >> f(-) >> f() y is undefined at x = >> f(4) 0.5000 EXERCISE 5 Write a function file that creates the following piecewise function: x x +, x f(x) = e x, < x 6 sin x + x, x > 6 Assume x is a scalar. The function file should contain an if statement to distinguish between the different cases. The function should also display the function is undefined at x = - if the input is x =. Test your function by evaluating f( ), f(0), f(), f(), f(6) and f(8). DISTRIBUTED - c 08 Stefania Tracogna, SoMSS, ASU 8