Lecture4 Arrays
Lecture4 Arrays
CSE, POSTECH
Introduction
Data is often available in tabular form
Tabular data is often represented in arrays
Matrix is an example of tabular data and is often
represented as a 2-dimensional array
– Matrices are normally indexed beginning at 1 rather
than 0
– Matrices also support operations such as add, multiply,
and transpose, which are NOT supported by C++’s 2D
array
2
Introduction
It is possible to reduce time and space using a
customized representation of multidimensional
arrays
This chapter focuses on
– Row- and column-major mapping and representations of
multidimensional arrays
– the class Matrix
– Special matrices
Diagonal, tridiagonal, triangular, symmetric, sparse
3
1D Array Representation in C++
Memory
a b c d
start
1-dimensional array x = [a, b, c, d]
map into contiguous memory locations
location(x[i]) = start + i
Space Overhead
Memory
a b c d
start
a b c d
4 separate
e f g h
1-dimensional arrays
i j k l
a b c d
e f g h
i j k l
16
Row- and Column-Major Mappings
Row-major order mapping functions
map(i1,i2) = i1u2+i2 for 2D arrays
map(i1,i2,i3) = i1u2u3+i2u3+i3 for 3D arrays
x[]
2 3
4 5 6
7 8 9 l0
20
Matrix Operations
Transpose
– The result of transposing an m x n matrix is an n x m
matrix with property:
MT(j,i) = M(i,j), 1 <= i <= m, 1 <= j <= n
Addition
– The sum of matrices is only defined for matrices that
have the same dimensions.
– The sum of two m x n matrices A and B is an m x n
matrix with the property:
C(i,j) = A(i,j) + B(i,j), 1 <= i <= m, 1 <= j <= n
21
Matrix Operations
Multiplication
– The product of matrices A and B is only defined when
the number of columns in A is equal to the number of
rows in B.
– Let A be m x n matrix and B be a n x q matrix. A*B will
produce an m x q matrix with the following property:
22
A Matrix Class
There are many possible implementations for
matrices.
// use a built-in 2 dimensional array
T matrix[m][n]
24