LAB 2 VECTORS AND MATRICES

Similar documents
Lecture 2: Variables, Vectors and Matrices in MATLAB

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

MATLAB: The Basics. Dmitry Adamskiy 9 November 2011

Introduction to Matlab

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

MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB

AMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA

Armstrong State University Engineering Studies MATLAB Marina 2D Arrays and Matrices Primer

MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB

A Quick Introduction to MATLAB/Octave. Kenny Marino, Nupur Chatterji

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

Introduction to MATLAB for Engineers, Third Edition

Introduction to MATLAB

Matlab- Command Window Operations, Scalars and Arrays

Dr Richard Greenaway

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

Introduction to MATLAB Programming

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

ECE Lesson Plan - Class 1 Fall, 2001

MATLAB for Experimental Research. Fall 2018 Vectors, Matrices, Matrix Operations

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

Matrices 4: use of MATLAB

MATLAB Lecture 1. Introduction to MATLAB

Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming usin

Lecture 2. Arrays. 1 Introduction

Arrays and Matrix Operations

Chapter 1 Introduction to MATLAB

Identity Matrix: >> eye(3) ans = Matrix of Ones: >> ones(2,3) ans =

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

Computational Mathematics

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

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

Using the fprintf command to save output to a file.

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

(Creating Arrays & Matrices) Applied Linear Algebra in Geoscience Using MATLAB

Dr. Iyad Jafar. Adapted from the publisher slides

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

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

1 Overview of the standard Matlab syntax

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

Introduction to MATLAB

An Introduction to MATLAB Programming

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

MATLAB Tutorial Matrices & Vectors MATRICES AND VECTORS

Introduction to MATLAB

Computational Photonics, Seminar 01 on Introduction into MATLAB, Page 1

0_PreCNotes17 18.notebook May 16, Chapter 12

Computer Packet 1 Row Operations + Freemat

MAT 343 Laboratory 2 Solving systems in MATLAB and simple programming

Introduction to MatLab. Introduction to MatLab K. Craig 1

Introduction to MATLAB

Introduction to MATLAB

Introduction to MATLAB. CS534 Fall 2016

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

Mathematics 4330/5344 #1 Matlab and Numerical Approximation

Matlab Introduction. Scalar Variables and Arithmetic Operators

Introduction to Matlab. By: Hossein Hamooni Fall 2014

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

How to Use MATLAB. What is MATLAB. Getting Started. Online Help. General Purpose Commands

Matrix Inverse 2 ( 2) 1 = 2 1 2

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

Introduction to MATLAB 7 for Engineers

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

Matrix Multiplication

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

ENGR 1181 MATLAB 02: Array Creation

Addition/Subtraction flops. ... k k + 1, n (n k)(n k) (n k)(n + 1 k) n 1 n, n (1)(1) (1)(2)

function [s p] = sumprod (f, g)

One-dimensional Array

ME305: Introduction to System Dynamics

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

Module 6: Array in C

Introduction and MATLAB Basics

Basics. Bilkent University. CS554 Computer Vision Pinar Duygulu

MATLAB GUIDE UMD PHYS401 SPRING 2012

Lecture 5: Matrices. Dheeraj Kumar Singh 07CS1004 Teacher: Prof. Niloy Ganguly Department of Computer Science and Engineering IIT Kharagpur

Matrix Multiplication

How to declare an array in C?

Fundamentals of MATLAB Usage

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

Arithmetic operations

CS129: Introduction to Matlab (Code)

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

NatSciLab - Numerical Software Introduction to MATLAB

x = 12 x = 12 1x = 16

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

Getting To Know Matlab

ELEN E3084: Signals and Systems Lab Lab II: Introduction to Matlab (Part II) and Elementary Signals

Linear Algebra in LabVIEW

Operators. Java operators are classified into three categories:

The Mathematics of Big Data

Introduction to Matlab

Twister: Language Reference Manual

Teaching Manual Math 2131

6.094 Introduction to MATLAB January (IAP) 2009

McTutorial: A MATLAB Tutorial

Computer Vision. Matlab

CITS2401 Computer Analysis & Visualisation

CMAT Language - Language Reference Manual COMS 4115

Introduction to MATLAB

Transcription:

EN001-4: Intro to Computational Design Tufts University, Department of Computer Science Prof. Soha Hassoun LAB 2 VECTORS AND MATRICES 1.1 Background Overview of data types Programming languages distinguish different types of data; every piece of data is associated with a data type. MATLAB stores all numeric values as a double-precision floatingpoint number, or double for short. This default cannot be changed. MATLAB has other data types, such as logicals (which we will discuss later) and characters (char). Matrices in MATLAB store data. All elements of any matrix must have the same type. For example, you can create a matrix of doubles or a matrix oflogical True/False variables. MATLAB provides powerful built-in functions to perform arithmetic (e.g., * for matrix multiplication) and logical (e.g., greater than a particular value) operations on matrices. In this lab, we will work with matrices of double. The learning objectives of this lab are: Construct and examine data types Create vectors, access and modify elements within them, and perform vector-vector and scalar-vector operations Create matrices, access and modify elements within them, and perform matrix-matrix and scalar-matrix operations Explain column-major ordering for matrices Become familiar with many built-in matrix-based MATLAB functions including find, sum, isempty, etc You should read the Background sections first, and cut/paste the code into a MATLAB window to verify what it does and to play with it yourself. 1.2 Background: looking at data types All MATLAB variables belong to a class. Each class has different characteristics. When MATLAB encounters a new variable name, it creates the variable and allocates the proper storage for it according to its class. Each MATLAB variable is stored in an array. For example, performing the operation a = 8, allocates storage for an array of size 1x1, and labels that storage as a. By default, MATLAB stores all numeric variables as doubleprecision floating-point values. This means that MATLAB allocates 64-bits (8 bytes) of storage to hold this value. You can examine the data type of a variable using the whos command. 1

2 LAB 2VECTORS AND MATRICES EXAMPLE 1.1 Examining Data Types >> a = 8 a = 8 >>whos Name Size Bytes Class Attributes a 1x1 8 double 1.3 Background: creating vectors We can think of a vector as a 1-dimensional array (collection) with several elements. A row vector that holds n data points has the dimension 1 n. A vector can be defined using an assignment operator, and can be specified by explicitly listing each element or by using the colon operator to generate the vector iteratively with the proper step size (first:step:last). The size of the vector can be obtained using the keyword size, and two values are returned. The first refers to the 1 dimensional nature of the vector. The second refers to the number of elements in the vector. You can use the length command, which returns the largest dimension of the vector. Alternatively, you can use numel(v) to obtain the number of elements in the vector. To create a vector of all ones, or all zeros, MATLAB provides special functions called ones and zeros. An empty vector is created using the empty square brackets, [ ]. An element (or more) is deleted by assigning the particular vector element(s) to [ ]. EXAMPLE 1.2 Creating Vectors >> v=[20 30 40 50] v = 20 30 40 50 >> v2 = 20:10:50 v2 = 20 30 40 50 >> size(v2) 1 4

BACKGROUND: ACCESSING AND MODIFYING ELEMENTS WITHIN A VECTOR 3 >> v = ones(1, 5) v = 1 1 1 1 1 >> v = [] v = [] 1.4 Background: accessing and modifying elements within a vector Elements in a vector are numbered sequentially starting with element number 1. The n th element of vector v can be accessed using the parenthesis notation, v(n). A subset of the vector, from element i to element k inclusive, can be accessed using subscripted indexing via the range notation, v(i : k). Assignment to an individual element is performed using the assignment operator. Beware of out-of-range indexing. EXAMPLE 1.3 Accessing and Modifying Elements within a Vector >> v=[20 30 40 50] v = 20 30 40 50 >> v(2) = [] 20 40 50 >> v(2:3) = [] 20 >> v = [v 100 200 300 400] v = 20 100 200 300 400

4 LAB 2VECTORS AND MATRICES 1.5 Background: vector operations MATLAB provides scalar operations that perform the same operation on each individual element within a vector. For example, the code v = v*3 will multiply every element of a vector v by 3. MATLAB also provides element-by-element operations that apply one vector to another of matching size on term-by-term basis. For example, if v1 and v2 are two vectors of the same dimensions, then v1 + v2 results in a vector of the same dimension where each element is the sum of the appropriate terms in v1 and v2. The difference between scalar and element-by-element operations is obvious from the context if one operand is a simple number, then it s a scalar operation. For a small number of operations (most notably, multiplication or * ), MATLAB provides yet a third type of operation. MATLAB allows you to do matrix multiplication (which you probably learned about in high-school), where you multiply entire rows and columns to multiply two matrices. To distinguish between element-by-element multiplication and matrix multiplication, MATLAB uses.* for the former and * for the latter. Addition and subtraction do not need any extra operators, since all addition of two matrices is element by element. EXAMPLE 1.4 Scalar and Array Operators on Vectors >> v1=[2 4 6] v1 = 2 4 6 >> v1*3 6 12 18 >> v2=[100 200 300] v2 = 100 200 300 >> v1.* v2 200 800 1800 >> v1 + v2

BACKGROUND: CONSTRUCTING MATRICES 5 102 204 306 1.6 Background: constructing matrices Creating a matrix is similar to creating a vector. Matrices are defined by entering the elements row by row separated by semicolons (;). You can also create a matrix of zeros or ones of any size using zeros or ones commands. A matrix of random numbers can be built by rand. size(a) returns the size of matrix A. EXAMPLE 1.5 Constructing Matrices >> m1=[1 2 3; 4 5 6] m1 = 1 2 3 4 5 6 >> size(m1) 2 3 >> m2=zeros(4,2) m2 = 0 0 0 0 0 0 0 0 >> m3=ones(3,5) m3 = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 >> m4=rand(2,2) m4 = 0.7922 0.6557

6 LAB 2VECTORS AND MATRICES 0.9595 0.0357 1.7 Background: accessing and modifying elements within a matrix To reference a particular element of a matrix, specify its row and column number with the matrix name, A(row, column). When you index into the matrix A using only one subscript (e.g. A(5)), MATLAB treats A as if its elements were strung out in a long column vector, by going down the columns consecutively. You can select a submatrix of a given matrix by specifying the rows and columns to extract. You can use : to indicate all rows or columns of a matrix. EXAMPLE 1.6 Accessing and Modifying Elements within a Matrix >> m1=[1 2 3; 4 5 6]; >> m1(1,3) 3 >> m1(2,2) 5 >> m1(5) 3 >> m5=[1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]; >> m5([2 4], [2 3 4]) 6 7 8 14 15 16 >> m5(2,:) 5 6 7 8

BACKGROUND: MATRIX OPERATIONS 7 1.8 Background: matrix operations Matrices in MATLAB can be manipulated in many ways. For example, you can find the transpose of a matrix by apostrophe key ( ). Rows are changed to columns and columns are changed to rows. EXAMPLE 1.7 Matrix Transpose >> m1 1 4 2 5 3 6 There are 3 types of matrix multiplication in MATLAB: Scalar multiplication. A matrix is multiplied by a constant value. Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B where each element of C is C(i, j) = p k=1 A(i, k)b(k, j). Element-wise multiplication. This is a element by element multiplication (C = A.*B). EXAMPLE 1.8 Matrix Multiplication >> m6=[1 3 5; 2 4 7]; >> 3 * m6 3 9 15 6 12 21 >> m7=[-5 8 11; 3 9 21; 4 0 8]; >> m6*m7 24 35 114 30 52 162 >> m8=[2 6 7; 1 4 2]; >> m6.*m8

8 LAB 2VECTORS AND MATRICES 2 18 35 2 16 14 To test the equality of two matrices, you can use isqual(a, B) where A and B are the matrices. isequal returns 1 if the matrices are numerically equal. Otherwise, it returns 0. EXAMPLE 1.9 Matrix Equality >> m9=[1 2 3; 4 5 6]; >> m10=[1 2 3; 4 5 6]; >> m11=[6 7 8; 9 10 2]; >> isequal(m9, m10) 1 >> isequal(m10, m11) 0 1.9 Background: the find function and column-major ordering The find function locates elements within a matrix that meet particular criterion. The command, ind = find(a), locates all nonzero elements of A and and returns the linear indices of those elements in vector ind. The command, find(a>x), returns the indices for the elements of A that are greater than x. Here, it is important to realize that MATLAB indexes its elements in a notation called, column major. Column-major order refers to arranging multidimensional arrays in linear fashion such that consecutive elements of the columns are contiguous. For a 2 by 2 matrix, element A(1,1) will be the first element, and element A(2,1) is the second element, and element A(1,2) is the third element, and element A(2,2) is the fourth element. EXAMPLE 1.10 Using the find Function >> m=[0 2 0; 4 5 6] m = 0 2 0 4 5 6 >> find (m)

BACKGROUND: GREAT FUNCTIONS TO KNOW! 9 2 3 4 6 >> find (m>3) 2 4 6 1.10 Background: great functions to know! sum(a): Returns a row vector of the sums of each column inv(a): Calculates the inverse of matrix A det(a): Returns the determinant of the square matrix A. isempty(a): Returns 1 if A is empty eye(n): Generates the n by n identity matrix diag(a): Returns the main diagonal of matrix A triu(a): Returns the upper triangular part of A tril(a): Returns the lower triangular part of A 1.11 Problems Consider the following two matrices: A = [9 1 4 5 8; 6 2 0 3 4; 4 1 9 9 2; 5 2 9 4 4; 4 2 5 1 1] B = [1 2 2 5 2; 9 4 6 3 4; 10 8 7 7 6; 6 0 6 2 8; 1 0 5 7 10] To code the answers to these problems, create one new script and call it L2.m. You might want to write and debug each section; and then comment it out while writing the following section. MATLAB can comment out an entire block of code using the %{ and %} operators. Do not forget to uncomment *ALL* sections before turning in the assignment. Your code should display the answers in the order specified by the problem set, simply by not putting a semicolon (;) after the appropriate calculation. Also, make sure you write your name at the top of the script.

10 LAB 2VECTORS AND MATRICES 1. Create a vector V with values 100, 300, 500, 3, and 10. Use this vector for each part of the problem below. (a) Add 2 to every element in V. (b) Divide every element in V by 3 (using the original V, not the result of part (a)). (c) Square every element in V. 2. Given matrix A from above, (a) extract the 3rd row. (b) extract the 5th column. (c) extract a submatrix composed of rows 1, 3, 5 and columns 2, 4. (d) find the sum of column 5. In each case, use the original matrix A for each sub-problem, rather than the result of the previous sub-problem. 3. Given matrices A and B from above, (a) calculate the inverse of matrix A (b) sum the elements in matrices A and B (c) perform matrix multiplication of A and B (d) perform element-wise multiplication of A and B. 4. Given matrices A and B from above, (a) use the sum command to sum all columns of matrix B (b) sum all rows of matrix B (c) sum all entries in matrix B 5. Use the find and sum commands to sum all entries in B greater than 5.