SNU IDB Lab. Ch8. Arrays and Matrices © copyright 2006 SNU IDB Lab.

Slides:



Advertisements
Similar presentations
Sparse Matrices sparse … many elements are zero dense … few elements are zero.
Advertisements

CS 450: COMPUTER GRAPHICS LINEAR ALGEBRA REVIEW SPRING 2015 DR. MICHAEL J. REALE.
Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Arrays and Matrices CSE, POSTECH. 2 2 Introduction Data is often available in tabular form Tabular data is often represented in arrays Matrix is an example.
Linear Algebra.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Matrices CSE, POSTECH.
Arrays.
Arrays. 1D Array Representation In C 1-dimensional array x = [a, b, c, d] map into contiguous memory locations Memory abcd start location(x[i]) = start.
1.7 Diagonal, Triangular, and Symmetric Matrices.
ECE122 L14: Two Dimensional Arrays March 27, 2007 ECE 122 Engineering Problem Solving with Java Lecture 14 Two Dimensional Arrays.
1 2-D Arrays Overview l Why do we need Multi-dimensional array l 2-D array declaration l Accessing elements of a 2-D array l Declaration using Initializer.
Chapter 9 Graph algorithms Lec 21 Dec 1, Sample Graph Problems Path problems. Connectedness problems. Spanning tree problems.
Alice in Action with Java
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
C++ for Engineers and Scientists Third Edition
Introduction of Arrays. Arrays Array form an important part of almost all programming language. It provides a powerful feature and can be used as such.
MOHAMMAD IMRAN DEPARTMENT OF APPLIED SCIENCES JAHANGIRABAD EDUCATIONAL GROUP OF INSTITUTES.
Matrix table of values
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Graph Operations And Representation. Sample Graph Problems Path problems. Connectedness problems. Spanning tree problems.
Group members: M.Shozib, Hasnain Khan, M.Awais, Shahid Rafiq Asad ali.
1.7 Diagonal, Triangular, and Symmetric Matrices 1.
Java Unit 9: Arrays Declaring and Processing Arrays.
Compiled By Raj G. Tiwari
Presentation on Matrices and some special matrices In partial fulfillment of the subject Vector calculus and linear algebra ( ) Submitted by: Agarwal.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Arrays and Matrices 황승원 Fall 2010 CSE, POSTECH. 2 2 Any real-life matrix you know?
Copyright © 2012 Pearson Education, Inc. Chapter 8 Two Dimensional Arrays.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
COSC 1P03 Introduction to Data Structures 1.1 COSC 1P03  Audience  planning to major in COSC (prereq. 1P02 60%)  Lectures (AS202, AS217), labs (J301),
Lecture Contents Arrays and Vectors: Concepts of array. Memory index of array. Defining and Initializing an array. Processing an array. Parsing an array.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Data Strcutures.
Two dimensional arrays in Java Computer Science 3 Gerb Objective: Use matrices in Java.
CHAPTER: 12. Array is a collection of variables of the same data type that are referenced by a common name. An Array of 10 Elements of type double.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Linear algebra: matrix Eigen-value Problems Eng. Hassan S. Migdadi Part 1.
Data Structure Sang Yong Han Chung-Ang University Spring
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
Graphs 황승원 Fall 2010 CSE, POSTECH. 2 2 Graphs G = (V,E) V is the vertex set. Vertices are also called nodes and points. E is the edge set. Each edge connects.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Sparse Matrices Matrix  table of values. Sparse Matrices Matrix  table of values Row 2 Column 4 4 x 5 matrix.
Matrices and Determinants
1 Arrays of Arrays Quick review … arrays Arrays of arrays ≡ multidimensional array Example: times table Representation in memory Ragged arrays Example:
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.
Arrays in java Unit-1 Introduction to Java. Array There are situations where we might wish to store a group of similar type of values in a variable. Array.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Two dimensional arrays A two dimensional m x n array A is a collection of m. n elements such that each element is specified by a pair of integers (such.
Chapter 9 Introduction to Arrays Fundamentals of Java.
1 Objective To provide background material in support of topics in Digital Image Processing that are based on matrices and/or vectors. Review Matrices.
Matrices. Variety of engineering problems lead to the need to solve systems of linear equations matrixcolumn vectors.
Introduction Types of Matrices Operations
Arrays. 1D Array Representation In C++ 1-dimensional array x = [a, b, c, d] map into contiguous memory locations Memory abcd start location(x[i]) = start.
C++ Arrays SarMag Trimester 31 C++ Arrays. C++ Arrays SarMag Trimester 32 C++ Arrays An array is a consecutive group of memory locations. Each group is.
Data Structure Sang Yong Han
Arrays.
Reminder: Array Representation In C++
بردارها و ماتريس ها ساختمان داده ها
Reminder: Array Representation In C++
Arrays.
Arrays.
Reminder: Array Representation In C++
Arrays and Matrices Prof. Abdul Hameed.
Presentation transcript:

SNU IDB Lab. Ch8. Arrays and Matrices © copyright 2006 SNU IDB Lab.

SNU IDB Lab. Data Structures 2 Bird’s-Eye View In practice, data are often in tabular form Arrays are the most natural way to represent it Want to reduce both the space and time requirements by using a customized representation This chapter Representation of a multidimensional array Row major and column major representation Develop the class Matrix Represent two-dimensional array Indexed beginning at 1 rather than 0 Support operations such as add, multiply, and transpose Introduce matrices with special structures Diagonal, triangular, and symmetric matrices Sparse matrix

SNU IDB Lab. Data Structures 3 Table of Contents Arrays Matrices Special Matrices Sparse Matrices

SNU IDB Lab. Data Structures 4 The Abstract Data Type: Array AbstractDataType Array { instances set of (index, value) pairs, no two pairs have the same index operations get(index) : return the value of the pair with this index set(index, value) : add this pair to set of pairs, overwrite existing one (if any) with the same index }

SNU IDB Lab. Data Structures 5 Indexing a Java Array Arrays are a standard data structure in Java The index (subscript) of an array in Java [ i 1 ] [ i 2 ] [ i 3 ]… [ i k ] Creating a 3-dimensional array score int [][][] score = new int [ u 1 ][ u 2 ] [ u 3 ] Java initializes every element of an array to the default value for the data type of the array’s components Primitive data types vs. User-defined data types

SNU IDB Lab. Data Structures 6 1-D Array Representation Similar in C, C++, Java 1-dimensional array x = [a, b, c, d] X[0], X[1], X[2], X[3] Map into contiguous memory locations location(x[i]) = start + i Space overhead of array declaration 4 bytes for start + 4 bytes for x.length = 8 bytes Excluding space needed for the elements of x Memory abcd start

SNU IDB Lab. Data Structures 7 2-D Arrays The elements of a 2-dimensional array “a” declared as int [][] a = new int[3][4]; May be shown as table a[0][0]a[0][1] a[0][2] a[0][3] a[1][0]a[1][1] a[1][2] a[1][3] a[2][0]a[2][1] a[2][2] a[2][3] a[0][0] a[0][1] a[0][2] a[0][3] row 0 a[1][0] a[1][1] a[1][2] a[1][3] row 1 a[2][0] a[2][1] a[2][2] a[2][3] row 2 column 0column 1column 2column 3

SNU IDB Lab. Data Structures 8 “Array of arrays” Representation (1) Same in Java, C, and C++ 2D array is represented as a 1D array The 1D array’s each element is, itself, a 1D array int [][] x = new int[3][5] A 1D array “x” (length 3) Each element of x is a 1D array (length 5) x[0] x[1] x[2] [0][1] [2][3][4]

SNU IDB Lab. Data Structures 9 “Array of arrays” Representation (2) 2-D array x[][] a, b, c, d e, f, g, h i, j, k, l View 2-D array as 1-D arrays of rows x = [row0, row1, row2] row 0 = [a, b, c, d] row 1 = [e, f, g, h] row 2 = [i, j, k, l] So, require contiguous memory of size 3, 4, 4, and 4 respectively abcd efgh ijkl x[]

SNU IDB Lab. Data Structures 10 “Array of arrays” representation (3) Space overhead for array declaration = overhead for 4 1-D arrays = (num of rows + 1) x (start pointer + length variable) = 4 * 8 bytes = 32 bytes abcd efgh ijkl x[]

SNU IDB Lab. Data Structures 11 Covert 2D Array into 1D Array through Row-Major Mapping (1) Example 3 x 4 array a, b, c, d e, f, g, h i, j, k, l Convert into 1-D array y by collecting elements by rows Within a row elements are collected from left to right Rows are collected from top to bottom We get y[] = {a, b, c, d, e, f, g, h, i, j, k, l} row 0 row 1row 2…row i

SNU IDB Lab. Data Structures 12 Locating Element x[i][j] Assume x has r rows and c columns Each row has c elements There are i rows to the left of row i starting with x[i][0] So i * c elements to the left of x[i][0] So x[i][j] is mapped to position of i * c + j of the 1D array Ex: In the previous slide, c = 4: then x[2][3]  2*4 + 3  11 th element of 1D array row 0 row 1row 2…row i Covert 2D Array into 1D Array through Row-Major Mapping (2)

SNU IDB Lab. Data Structures 13 Space Overhead for 2D array Assume x has r rows and c columns 4 bytes for start + 4 bytes for length + 4 bytes for c = 12 bytes number of rows r = length / c Total space for 1D array: 12 + length Disadvantage: should have contiguous memory of size length row 0 row 1row 2…row i Start Length: length of 1D array C: number of columns Covert 2D Array into 1D Array through Row-Major Mapping (3)

SNU IDB Lab. Data Structures 14 a, b, c, d e, f, g, h i, j, k, l Convert into 1D array y by collecting elements by columns Within a column elements are collected from top to bottom Columns are collected from left to right We get y = {a, e, i, b, f, j, c, g, k, d, h, l} Covert 2D Array into 1D Array through Column-Major Mapping

SNU IDB Lab. Data Structures 15 Irregular 2D Arrays Arrays with two or more rows that have a different number of elements Size[i] for i (i is the row number) abcd efg ijkl x[] h k X[0] = new int [6] X[1] = new int [3] X[2] = new int [5]

SNU IDB Lab. Data Structures 16 Creating an Irregular 2D Array public static void main(String[] args) { int numofRows = 5; int [] size = (6,3,4,2,7) // declare a 2D array variable and allocate the desired number of rows int [][] irregularArray = new int [numOfRows][]; // now allocate space for the elements in each row for (int i = 0; i < numOfRows; i++) irregularArray[i] = new int [size[i]]; // use the array like any regular array irregularArray[2][3] = 5; irregularArray[4][6] = irregularArray[2][3] + 2; irregularArray[1][1] += 3; ….…. }

SNU IDB Lab. Data Structures 17 Table of Contents Arrays Matrices Special Matrices Sparse Matrices

SNU IDB Lab. Data Structures 18 Matrix Table of values has as rows and columns like 2-D array but numbering begins at 1 rather than 0 a b c d row 1 e f g h row 2 i j k l row 3 Use notation x(i, j) rather than x[i][j] Sometimes, we may use Java’s 2-D array or Vector to represent a matrix

SNU IDB Lab. Data Structures 19 Java 2D Array or Vector for a Matrix Java 2D Array A[0,*] and A[*,0] of 2D array cannot be used No support matrix operations such as add, transpose, multiply…. x and y are 2D arrays, we cannot do x + y, x – y, x * y, etc. directly in java Java Vector for 3X3 matrix Vector matrix_a = new Vector (3); Vector row_a = new Vector(3); row_a.addElement(“a”); row_a.addElement(“b”); row_a.addElement(“c ”); Vector row_b = new Vector(3); row_a.addElement(“d”); row_a.addElement(“e”); row_a.addElement(“f”); Vector row_c = new Vector(3); row_a.addElement(“g”); row_a.addElement(“h”); row_a.addElement(“i”); matrix_a.addElement(row_a); matrix_a.addElement(row_b); matrix_a.addElement(row_c) No matrix operations So, need to develop a class Matrix for object-oriented support of all matrix operations

SNU IDB Lab. Data Structures 20 The Class Matrix Uses 1-D array “element” to store a matrix in row-major order The CloneableObject interface has clone() and copy() public class Matrix implements CloneableObject { int rows, cols; // matrix dimensions Object [] element; // element array public Matrix(int theRows, int theColumns) { rows = theRows; cols = theColumns; element = new Object [ rows * cols]; }

SNU IDB Lab. Data Structures 21 clone() & copy() of Matrix public Object clone() { // return a clone of the matrix Matrix x = new Matrix(rows, cols); for (int i=0; i < rows * cols; i++) x.element[i] = ((CloneableObject) element[i]).clone(); return x; } public void copy (Matrix m) { // copy the references in m into this if (this != m) { rows = m.rows; cols = m.cols; element = new Object[rows * cols]; for (int i=0; i < rows * cols; i++) element[i] = m.element[i]; // copy each reference }

SNU IDB Lab. Data Structures 22 clone() & copy() example Matrix x = new Matrix(2, 2); for (int i=0; i < rows * cols; i++) x.element[i] = new Integer(i); // x = [0][1] // [2][3] Matrix y = x.clone(); // y = [0][1] // [2][3] ================================================== Matrix x = new Matrix(2, 2); Matrix y = new Matrix(2, 2); for (int i=0; i < rows * cols; i++) x.element[i] = new Integer(i*2); // x = [0][2] // [4][6] y.copy(x); // change y's member variables to make y same as x // y = [0][2] // [4][6] }

SNU IDB Lab. Data Structures 23 get() & set() of Matrix the element this[i, j] IndexOutOfBoundsException when i or j invalid */ public Object get (int i, int j) { checkIndex(i, j); // validate index return element[(i – 1) * cols + j -1]; } /**set this(i, j) = newValue IndexOutOfBoundsException when i or j invalid */ public void set (int i, int j, Object newValue) { checkIndex(i, j); element[(i – 1) * cols + j – 1] = newValue; }

SNU IDB Lab. Data Structures 24 add() of Matrix the this + m IllegalArgumentException when matrices are incomputible */ public Matrix add (Matrix m) { if (rows != m.rows || cols != m.cols) throw new IllegalArgumentException(“Imcompatible”); // create result matrix w Matrix w = new Matrix(rows, cols); int numberOfTerms = rows * cols; for ( int i=0; i < numberOfTerms; i++) w.element[i] = ((Computable) element[i]).add(m.element[i])); return w; }

SNU IDB Lab. Data Structures 25 Complexity of Matrix operations Constructor: 0 (rows * cols) Clone(), Copy(), Add(): 0 (rows * cols) Multiply(): 0 (this.row * this.cols * m.cols) Program 8.6 at pp 270

SNU IDB Lab. Data Structures 26 Table of Contents Arrays Matrices Special Matrices Sparse Matrices

SNU IDB Lab. Data Structures 27 Special Matrix Definitions Diagonal Matrix  M(i, j) = 0 for i = j Tridiagonal Matrix  M(i, j) = 0 for |i – j| > 1 Lower Triangular Matrix  M(i, j) = 0 for i < j Upper Triangular Matrix  M(i, j) = 0 for i > j Symmetric Matrix  M(i, j) = M(j, i) for all i, j

SNU IDB Lab. Data Structures 28 Diagonal Matrix An n x n matrix in which all nonzero terms are on the diagonal x(i, j) is on diagonal iff i = j Number of diagonal elements in an n x n matrix is n Non diagonal elements are zero Store diagonal only vs store n 2 whole

SNU IDB Lab. Data Structures 29 The Class DiagonalMatrix public class DiagonalMatrix { int rows; // matrix dimension (no cols!) Object zero; // zero element Object [] element; // element array public DiagonalMatrix (int theRows, Object theZero) { if (theRow 0”); rows = theRows; zero = theZero; for (int i=0; i<rows; i++) element[i] = zero; //construct only the diagonal elements }

SNU IDB Lab. Data Structures 30 get() and set() for DiagonalMatrix public Object get (int i, int j) { checkIndex(i, j); // validate index if (i == j) return element[i – 1]; // return only the diagonal element else return zero; // nondiagonal element } public void set (int i, int j, Object newValue) { if (i == j) element[i – 1] = newValue; // save only the diagonal element else // nondiagonal element, newValue must be zero if (!((Zero)newValue).equalsZero()) throw new IllegalArgumenetException(“must be zero”); }

SNU IDB Lab. Data Structures 31 Tridiagonal Matrix The nonzero elements lie on only the 3 diagonals Main diagonal: M(i, j) where i = j Diagonal below main diagonal: M(i, j) where i = j + 1 Diagonal above main diagonal: M(i, j) where j = j

SNU IDB Lab. Data Structures 32 Lower Triangular Matrix (LTM) An n x n matrix in which all nonzero terms are either on or below the diagonal x(i, j) is part of lower triangular iff i >= j Number of elements in lower triangle: … + n = n*(n+1) / 2 Store only the lower triangle

SNU IDB Lab. Data Structures 33 “Array of Arrays” Representation of LTM Use an irregular 2D array lengths of rows are not required to be the same x[] 789l0

SNU IDB Lab. Data Structures 34 1D Array representation of LTM (1) Use row-major order, but omit terms that are not part of the lower triangle For the matrix We get 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 How we can locate X[2][3]?

SNU IDB Lab. Data Structures 35 1D Array representation of LTM (2) Index of Element[i][j] Order is: row 1, row 2, row 3, … Row i is preceded by rows 1, 2, …, i-1 Size of row i is i Number of elements that precede row i is … + (i-1) = i * (i-1)/2 So element (i,j) is at position i * (i-1)/2 + j - 1 of the 1D array

SNU IDB Lab. Data Structures 36 Table of Contents Arrays Matrices Special Matrices Sparse Matrices

SNU IDB Lab. Data Structures 37 Sparse Matrices Sparse matrix  Many elements are zero Dense matrix  Few elements are zero The boundary between a dense and a sparse matrix is not precisely defined Structured sparse matrices Diagonal matrix Tridiagonal matrix Lower triangular matrix May be mapped into a 1D array so that a mapping function can be used to locate an element

SNU IDB Lab. Data Structures 38 Unstructured Sparse Matrices (USM) (1) Airline flight matrix: Aflight(n, n) airports are numbered 1 through n (say 1000 airports) Aflight(i, j) = list of nonstop flights from airport i to airport j 1000 x 1000 array of list references (4 bytes) to nonstop flight lists need 4,000,000 bytes (4G) However, only total number of flights = 20,000 (say) need at most 20,000 list references  at most 80,000 bytes (80M) We need an economic representation!

SNU IDB Lab. Data Structures 39 Unstructured Sparse Matrices (USM) (2) Web page matrix: WEBPM(n, n) Millions of trillions of web pages (numbered 1 through n) WEBPM(i, j) = number of links from page i to page j The number of links is very very smaller than the number of web pages Web analysis authority page: page that has many links to it hub page: page having links to many authority pages Facts of Web Links Roughly n = 2 billion pages (and growing by 1 million pages a day) n x n array of ints  16 * bytes (= 16 * 10 9 GB) Each page links to 10 (say) other pages on average On average there are 10 nonzero entries per row  20 billion links Space needed for nonzero elements is approximately 20 billion x 4 bytes = 80 billion bytes (= 80 GB)

SNU IDB Lab. Data Structures 40 Representation of USM Conceptualized into linear list in row-major order Scan the nonzero elements of the sparse matrix in row-major order Each nonzero element is represented by a triple (row, column, value) list = row column value

SNU IDB Lab. Data Structures 41 Implementations of USM Naive Implementation of USM Do not consider numerous elements having 0 Java 2D array Implementation Methods after conceptualizing Linear List Array Linked List (Chain) Orthogonal List

SNU IDB Lab. Data Structures 42 USM implementation using Array Linear List row list = column value element[] row column value

SNU IDB Lab. Data Structures 43 USM Implementation through Chain -- One Linear List Per Row row1 = [(3, 3), (5,4)] row2 = [(3,5), (4,7)] row3 = [] row4 = [(2,2), (3,6)] USM may be viewed as “array of linear list”  Synonym: Array of row chains

SNU IDB Lab. Data Structures 44 USM implementation using Array of Row Chains row[] 33 nul l next valuecol

SNU IDB Lab. Data Structures 45 USM implementation using Orthogonal Lists Both row and column lists More expensive than array of row chains More complicated implementation Not much advantage! Node structure rowcol nextdown value

SNU IDB Lab. Data Structures 46 Row Lists null n n n row list[]

SNU IDB Lab. Data Structures 47 Column Lists n n n column list[]

SNU IDB Lab. Data Structures 48 Orthogonal Lists null nn n nn n column list[] row list[]

SNU IDB Lab. Data Structures 49 Approximate Memory Requirements 500 x 500 matrix with 1994 nonzero elements Java 2D array: 500 x 500 x 4 bytes = 1G bytes Single Array Linear List: 3 x 4 bytes X 1994 = 23,928 = 24M bytes One Chain Per Row: x 4 = 25,928 = 26M bytes Orthogonal List: your job! row[] element[] row column value nu ll 45

SNU IDB Lab. Data Structures 50 Performance of Sparse Matrix implementations Matrix Transpose() with 500 x 500 matrix with 1994 nonzero elements Java 2D array 210 ms Array Linear List 6 ms One Chain Per Row 12 ms Matrix Addition with 500 x 500 matrices with 1994 and 999 nonzero elements Java 2D array 880 ms Array Linear List 18 ms One Chain Per Row 29 ms

SNU IDB Lab. Data Structures 51 Summary In practice, data are often in tabular form Arrays are the most natural way to represent it Reduce both the space and time requirements by using a customized representation This chapter Representation of a multidimensional array Row major and column major representation Develop the class Matrix Represent two-dimensional array Indexed beginning at 1 rather than 0 Support operations such as add, multiply, and transpose Introduce matrices with special structures Diagonal, triangular, and symmetric matrices Sparse matrix

SNU IDB Lab. Data Structures 52 JDK class: javax.vecmath.GMatrix public class Gmatrix { constructors GMatrix(int nRow, int nCol): Constructs an array of size nRow*nCol methods void add(GMatrix m1): Adds m1 to the matrix void sub(GMatrix m1): Subtracts m1 from the matrix void mul(GMatrix m1): Multiplies m1 to the matrix void negate(): Negates the matrix void transpose(): Transposes the matrix void invert(): Inverts the matrix double trace(): Returns the trace of the matrix }