Matrix algebra. Basics

Similar documents
II.Matrix. Creates matrix, takes a vector argument and turns it into a matrix matrix(data, nrow, ncol, byrow = F)

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

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

STAT 540: R: Sections Arithmetic in R. Will perform these on vectors, matrices, arrays as well as on ordinary numbers

Introduction to MATLAB

Computer Packet 1 Row Operations + Freemat

x = 12 x = 12 1x = 16

Therefore, after becoming familiar with the Matrix Method, you will be able to solve a system of two linear equations in four different ways.

MBV4410/9410 Fall Bioinformatics for Molecular Biology. Introduction to R

Stat 579: Objects in R Vectors

Matrix Inverse 2 ( 2) 1 = 2 1 2

PetShop (BYU Students, SIGGRAPH 2006)

Matrix Multiplication

Arrays, Matrices and Determinants

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

Matrix Multiplication

AH Matrices.notebook November 28, 2016

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

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

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

- ST Computer Intensive Statistical Analytics I Appendix: R basics

1 Matrices and Vectors and Lists

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

Chapter 1 Introduction to MATLAB

Lab #10 Multi-dimensional Arrays

PC-MATLAB PRIMER. This is intended as a guided tour through PCMATLAB. Type as you go and watch what happens.

Teaching Manual Math 2131

Matrices. Chapter Matrix A Mathematical Definition Matrix Dimensions and Notation

2 Second Derivatives. As we have seen, a function f (x, y) of two variables has four different partial derivatives: f xx. f yx. f x y.

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

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

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

Introduction to MATLAB

Package slam. February 15, 2013

Lecture 2: Variables, Vectors and Matrices in MATLAB

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

Introduction to R. UCLA Statistical Consulting Center R Bootcamp. Irina Kukuyeva September 20, 2010

Convert Local Coordinate Systems to Standard Coordinate Systems

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

Package slam. December 1, 2016

Maths for Signals and Systems Linear Algebra in Engineering. Some problems by Gilbert Strang

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

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

CT5510: Computer Graphics. Transformation BOCHANG MOON

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

Groups, Linear Algebra, and the Geometry of the Torus

R is a programming language of a higher-level Constantly increasing amount of packages (new research) Free of charge Website:

1 Overview of the standard Matlab syntax

Extremely short introduction to R Jean-Yves Sgro Feb 20, 2018

Workshop in Methods and Indiana Statistical Consulting Center Introduction to R

MATLAB Tutorial Matrices & Vectors MATRICES AND VECTORS

Introduction to MATLAB

Arrays and Matrix Operations

Meeting 1 Introduction to Functions. Part 1 Graphing Points on a Plane (REVIEW) Part 2 What is a function?

An Introductory Guide to R

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

The Mathematics of Big Data

Matrices 4: use of MATLAB

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

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

Teachers Teaching with Technology (Scotland) Teachers Teaching with Technology. Scotland T 3. Matrices. Teachers Teaching with Technology (Scotland)

Machine Learning for Signal Processing Fundamentals of Linear Algebra

Mathematical Operations with Arrays and Matrices

Package blockmatrix. February 19, 2015

University of Alberta

Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS

LAB 2 VECTORS AND MATRICES

Introduction to MATLAB LAB 1

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University

Variable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3.

Linear Algebra Review

ft-uiowa-math2550 Assignment HW8fall14 due 10/23/2014 at 11:59pm CDT 3. (1 pt) local/library/ui/fall14/hw8 3.pg Given the matrix

1 2 (3 + x 3) x 2 = 1 3 (3 + x 1 2x 3 ) 1. 3 ( 1 x 2) (3 + x(0) 3 ) = 1 2 (3 + 0) = 3. 2 (3 + x(0) 1 2x (0) ( ) = 1 ( 1 x(0) 2 ) = 1 3 ) = 1 3

Vector Calculus: Understanding the Cross Product

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

MATH 423 Linear Algebra II Lecture 17: Reduced row echelon form (continued). Determinant of a matrix.

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

Overview. Linear Algebra Notation. MATLAB Data Types Data Visualization. Probability Review Exercises. Asymptotics (Big-O) Review

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

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

Practice for Learning R and Learning Latex

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

Introduction to MatLab. Introduction to MatLab K. Craig 1

Introduction to Matlab

Put the following equations to slope-intercept form then use 2 points to graph

A Guide for the Unwilling S User

Package svd. R topics documented: September 26, 2017

WEEK 4 REVIEW. Graphing Systems of Linear Inequalities (3.1)

Basic matrix math in R

Matrix Multiplication

Getting Started with MATLAB

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

SML: Specialized Matrix Language White Paper

Logical operators: R provides an extensive list of logical operators. These include

Introduction to MATLAB

Machine Learning for Signal Processing Fundamentals of Linear Algebra

Dr Richard Greenaway

CDA5530: Performance Models of Computers and Networks. Chapter 8: Using Matlab for Performance Analysis and Simulation

Engineering Methods in Microsoft Excel. Part 1:

Input/Output Machines

Transcription:

Matrix.1 Matrix algebra Matrix algebra is very prevalently used in Statistics because it provides representations of models and computations in a much simpler manner than without its use. The purpose of this section is to provide the basics of commonly used matrix algebra operations in R. The program used in this section is basic_matrix_algebra.r. Basics A matrix is simply a rectangular arrangement of elements in rows and columns. For example, consider the matrix A as A = a 11 a 12 a 13 a 21 a 22 a 23 Letters that represent matrices are always bolded or written with a line underneath as A when bolding is not possible, like on a chalkboard. The symbolic elements of a matrix are written with a subscript for the row and column numbers (row, column). The dimension of the matrix is its number of rows and columns. For the above matrix, the dimension is 2 3. Consider the following two matrices: A = 1 2 3 4 5 6 and B = 1 10 1 5 5 8 Below is how we can enter these matrices into R and also perform addition and subtraction operations with them. > A <- matrix(data = c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE) > A [1,] 1 2 3 [2,] 4 5 6

Matrix.2 > class(a) [1] "matrix" > A[1, 1] [1] 1 > A[1, ] [1] 1 2 3 > A[, 1] [1] 1 4 > B <- matrix(data = c(-1, 10, -1, 5, 5, 8), nrow = 2, ncol = 3, byrow = TRUE) > B [1,] -1 10-1 [2,] 5 5 8 > A + B [1,] 0 12 2 [2,] 9 10 14 > A - B [1,] 2-8 4 [2,] -1 0-2 Comments: The matrix function allows one to enter a matrix. Often, it is best to enter the matrix as A <- matrix(data = c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE) so that the columns line up properly. This is how I usually write code in my own programs, but LYX re-formats the code here so it does not appear to occur. The byrow argument is very important! This instructs R to

Matrix.3 enter the elements listed in the data argument by rows. Thus, row #1 is filled with elements first before row #2. The default for this argument is byrow = FALSE. Thus, > matrix(data = c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) [1,] 1 3 5 [2,] 2 4 6 results in the elements in the data argument filling column 1 first. Notice that the class of A is matrix. Elements of a matrix can be referenced by their row and column numbers. A mathematical vector can be represented as a matrix class type or a type of its own: > y <- matrix(data = c(1, 2, 3), nrow = 3, ncol = 1, byrow = TRUE) > y [,1] [1,] 1 [2,] 2 [3,] 3 > class(y) [1] "matrix" > x <- c(1, 2, 3) > x [1] 1 2 3 > class(x) [1] "numeric" > is.vector(x) [1] TRUE

Matrix.4 This latter representation can present some confusion when vectors are multiplied with other vectors or matrices because no specific row or column dimensions are given. How to handle these situations will be discussed more shortly. Question: How can a 4 4 matrix of 1 s be created? Matrix multiplication Consider the following two matrices: A = 1 2 3 4 5 6 and B = 3 0 1 2 0 1 The syntax to multiply these matrices together is not simply * but %*%: > A <- matrix(data = c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE) > B <- matrix(data = c(3, 0, 1, 2, 0, 1), nrow = 3, ncol = 2, byrow = TRUE) > A %*% B [1,] 5 7 [2,] 17 16 > B %*% A [1,] 3 6 9 [2,] 9 12 15 [3,] 4 5 6 > A * B Error: > A * A non-conformable arrays [1,] 1 4 9 [2,] 16 25 36 > 3 * A [1,] 3 6 9 [2,] 12 15 18

Matrix.5 The * alone denotes element-by-element multiplication. When * is used with a scalar value and a matrix, each element of the matrix is multiplied by the scalar as would be expected. Consider the mathematical vector of 1 x = 2 3 Below are some examples when working with what R considers to be a vector: > x <- c(1, 2, 3) > A %*% x [,1] [1,] 14 [2,] 32 > # Inner product > x %*% x # x'x [,1] [1,] 14 > # Outer product > x %o% x # xx' [1,] 1 2 3 [2,] 2 4 6 [3,] 3 6 9 How does R know to make x a 3 1 vector for Ax? How does R know to compute the result of x%*%x as x x? Here s what R says in its help for %*%: Multiplies two matrices, if they are conformable. If one argument is a vector, it will be promoted to either a row or column matrix to make the two arguments conformable. If both are vectors it will return the inner product. An inner product produces a scalar value. If you wanted xx, one can use the outer product %o%. Of course, if x is defined

Matrix.6 as x <- matrix(data = c(1, 2, 3), nrow = 3, ncol = 1, byrow = TRUE), all calculations occur as one would normally expect with matrix algebra. Inverse of a matrix There is no function named inverse to find an inverse of a matrix. Rather, the function is named solve(): > A <- matrix(data = c(1, 2, 3, 4), nrow = 2, ncol = 2, byrow = TRUE) > solve(a) [1,] -2.0 1.0 [2,] 1.5-0.5 > A %*% solve(a) [1,] 1 1.11e-16 [2,] 0 1.00e+00 > solve(a) %*% A [1,] 1.00e+00 0 [2,] 1.11e-16 1 The solve() function can also be used to solve for x in Ax = b, where A 1 Ax = A 1 b x = A 1 b. The syntax is solve(a,b). Question: Why is there no inverse function? More matrix operations Commonly used operations with matrices include finding the diagonal elements, forming a diagonal matrix, finding determinants, and taking a transpose of a matrix: > # Find diagonal elements of a matrix > A <- matrix(data = c(1, 2, 3, 4), nrow = 2, ncol = 2, byrow = TRUE) > A

Matrix.7 [1,] 1 2 [2,] 3 4 > diag(x = A) [1] 1 4 > # Create diagonal matrix using same function > diag(x = c(1, 2, 3, 4)) [,4] [1,] 1 0 0 0 [2,] 0 2 0 0 [3,] 0 0 3 0 [4,] 0 0 0 4 > # Determinant > det(a) [1] -2 > # Transpose > t(a) [1,] 1 3 [2,] 2 4 Question: How can a 4 4 identity matrix be created? Eigenvalues Eigenvalues and eigenvectors are found by using the eigen() function. > A <- matrix(data = c(1, 0.5, 0.5, 1.25), nrow = 2, ncol = 2, byrow = TRUE) > A [1,] 1.0 0.50 [2,] 0.5 1.25 > eigen(a) $values [1] 1.6404 0.6096

Matrix.8 $vectors [1,] 0.6154-0.7882 [2,] 0.7882 0.6154 > save.eig <- eigen(a) > names(save.eig) [1] "values" "vectors" > # Verify > A %*% save.eig$vectors[, 1] [,1] [1,] 1.010 [2,] 1.293 > save.eig$values[1] * save.eig$vectors[, 1] [1] 1.010 1.293 > # Verify > A %*% save.eig$vectors[, 2] [,1] [1,] -0.4805 [2,] 0.3752 > save.eig$values[2] * save.eig$vectors[, 2] [1] -0.4805 0.3752 > # Length of a vector > sqrt(sum(save.eig$vectors[, 1]^2)) [1] 1 > sqrt(sum(save.eig$vectors[, 2]^2)) [1] 1 To verify the eigenvectors, I used the relationship that eigenvectors of a matrix A satisfy Ab = λb where b is an eigenvector. Please remember that eigenvectors are not unique! Eigenvectors in R are scaled to have a length of 1. Still, there is more than one vector that can have a length of 1. I have seen 32-bit and 64-bit R produce different eigenvectors with the exact same code (each element multiplied by -1). Below is a plot of the eigenvectors to demonstrate that they are

Matrix.9 orthogonal: > # Square plot (default is 'm' which means maximal region) > par(pty = "s") > # Set up some dummy values for plot > b1 <- c(-1, 1) > b2 <- c(-1, 1) > plot(x = b1, y = b2, type = "n", main = "Eigenvectors of A", xlab = expression(b[1]), ylab = expression(b[2]), panel.first = grid()) > # Draw line on plot - h specifies a horizontal line > abline(h = 0, lty = "solid", lwd = 2) > # v specifies a vertical line > abline(v = 0, lty = "solid", lwd = 2) > # Draw eigenvectors > arrows(x0 = 0, y0 = 0, x1 = save.eig$vectors[1, 1], y1 = save.eig$vectors[2, 1], col = "red", lty = "solid") > arrows(x0 = 0, y0 = 0, x1 = save.eig$vectors[1, 2], y1 = save.eig$vectors[2, 2], col = "red", lty = "solid")

Matrix.10 Eigenvectors of A b 2 1.0 0.5 0.0 0.5 1.0 1.0 0.5 0.0 0.5 1.0 b 1 Additional comments All of the functions examined here are in R s base package. A web page that summarizes many useful functions for matrix algebra is http://statmethods.net/advstats/ matrix.html. There are many other packages available for matrix algebra. For example, the Matrix package has functions that are useful for sparse matrices. The bigalgebra package has functions that are useful for big matrices. See the Numerical Mathematics task view at https://cran.r-project.org/web/views/

Matrix.11 NumericalMathematics.html for more packages. A data frame can be coerced as.matrix(). into a matrix by using There are times when one needs to add a row or column of numbers to a matrix. For example, suppose A is a 10 2 matrix, and we need to add a leading column of 1 s to it. This can be done using cbind(1,a). R recycles the 1 so that a matrix of the same number of rows combines with A leading to a 10 3 matrix. The rbind() function can be used in a similar manner to add a row to a matrix. Because rbind() and cbind() are generic functions, they can also be useful with other types of objects like data frames. The dimnames argument of matrix() can be used to create names for the row and column dimensions. An example is given in my program.