Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

AP Computer Science 2-Dimensional Arrays

Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-dimensional, ... In
practice most arrays are one-dimensional, and two-dimensional (rows and columns) are also quite common. Higher dimensional arrays
are less common so they aren't used in the examples, but there's nothing mysterious about them and the same principles apply.
Two-dimensional arrays are used whenever the model data is best represented with rows and columns, or has two varying
aspects (eg, gender and age, weight and height, etc.).

Declaring and Creating 2-Dimensional Arrays

Example 1: We can create a 5 x 4 matrix of integer values in the following way

int[][] x = new int [5][4];

We can think of the matrix as follows:

Columns 
x x[0][0] x[0][1] x[0][2] x[0][3]
rows 

x[1][0] x[1][1] x[1][2] x[1][3]

x[2][0] x[2][1] x[2][2] x[2][3]

x[3][0] x[3][1] x[3][2] x[3][3]

x[4][0] x[4][1] x[4][2] x[4][3]

Accessing Elements in a 2-Dimensional Array

Elements can be referred to by references of the form x[row][column]. Each element x[row][col] is an int!

Example 2:

x[1][2] = 3;
x[1][1] = x[0][1] * 2;
Internal Representation of Arrays in Java

Although we can view the matrix as shown above, a much better understanding of the array can be gained though
understanding specifically how Java represents this data structure internally. Consider the following model.

x
 columns
x[0] x[0][0] x[0][1] x[0][2] x[0][3]

x[1] x[1][0] x[1][1] x[1][2] x[1][3]

rows x[2] x[2][0] x[2][1] x[2][2] x[2][3]

x[3] x[3][0] x[3][1] x[3][2] x[3][3]

x[4] x[4][0] x[4][1] x[4][2] x[4][3]

Let’s very carefully examine the declaration and creation of this data structure. In order to do this, we will break the declaration above
down into very basic steps. This will help you understand what 2D arrays are and how to work with them.

int[][]x;

This statement creates a variable x that can contain “an array of arrays of ints”. Following this statement we will have

Notice that there is NO array of integers. We have merely created a variable that can contain a reference to an array of arrays of ints.

Let’s continue. Now suppose we subsequently perform that statement

x = new int[5][];

This creates a one-dimensional array of 5 references to arrays of ints. Now things look like this…

x

x[0]

x[1]

rows x[2]

x[3]

x[4]

Notice that even after this statement, there is NO matrix. But we have created a one-dimensional array that will contain
references to the rows of the matrix. Each entry x[row] is a reference to a 1 dimensional array of int which represent that row of the
matrix.
Now let’s add a row of actual integers to the matrix.

x[0] = new int[4];

Now the structure will look like

x
 columns
x[0] 
x[0][0] x[0][1] x[0][2] x[0][3]

x[1]

rows x[2]

x[3]

x[4]

Let complete the construction of this array by creating the remaining 4 rows. We’ll do this using a loop.

for( int i=1; i < x.length; i++)


x[i] = new int[4];

Now the array has been completely created!

A key observation to make here is that there really are only 1-dimensional arrays! We represent 2-dimensional arrays as a
one dimensional array OF one dimensional arrays. We could represent a 3 dimensional array as a two dimensional array of one
dimensional arrays and so on.

Let’s make sure we understand what these various expressions represent.

Reference What type is it and what does it contain?


x The reference to the one dimensional array of references to one dimensional arrays
representing rows of the matrix
x[i] A reference to the one dimensional array of int’s that is row i of the matrix.
x[i][j] a int in row i, column j of the matrix.
Questions:

1) What does x.length represent?

2) What does x[0].length represent?

3) How do you calculate the number of values stored in an array?

4) What happens if we print x[5] or x[4][7]? Explain

You can create and initialize a 2 D array using initializer lists too. For example,

int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
Arrays can also be Ragged (although you are not as likely to see these). In a ragged array, the number of entries in each row varies.
As a result the array is not rectangular in structure. For example,

int[][] triangleArray = { 1 2 3 4 5
{1, 2, 3, 4, 5},
{2, 3, 4, 5}, 2 3 4 5
{3, 4, 5}, 33
{4, 5}, 3 4 5
{5}
}; 4 5
5

Question: What is triangleArray.length? triangleArray[2].length? triangleArray[0].length?

Internal representations of 2-Dimensional Arrays


How are 2-dimensional (and higher ) arrays stored in a computer’s memory. The first thing to realize is that a computers
memory is essentially a 1-dimensional array( i.e. it’s linear) of bytes. How then are higher dimensional data structures represented
with such a data structure?

There are essentially two ways to store 2-dimensional data commonly utilized: row-major order and column-major order.
Following standard matrix notation, rows are numbered by the first index of a two-dimensional array and columns by the second
index. Array layout is critical for correctly passing arrays between programs written in different languages.

Row-major order: In row-major storage, a Column-major order: Column-major order is a similar


multidimensional array in linear memory is organized such method of flattening arrays onto linear memory, but the
that rows are stored one after the other. columns are listed in sequence.

For example, consider this 2×3 array: The array

if declared in Java as
int[][] A = { {1, 2, 3}, {4, 5, 6} }; if stored contiguously in linear memory with column-major
order looks like the following:
is laid out contiguously in linear memory as:

1 4 2 5 3 6
1 2 3 4 5 6
Low Higher
Low Higher
address address
address address
AP Computer Science Programmin Assignment 14 (2D Arrays & Matrices) 2021

You probably recognize these things we call one and two-dimensional arrays from your prior math courses. One-dimensional arrays
are frequently called vectors and the one-dimensional array (from computer science)

x  2 -1
0 1

would be represented by the mathematical notation x = < 2, -1> and two-dimensional arrays are typically referred to as matrices.
For example the two-dimensional array (from computer science)

x
 columns
x[0]  2 -1

rows x[1]  10 -5

é ù
would be written in mathematical matrix notation as X = ê 2 -1 ú
ë 10 -5 û

Now that we have defined matrices, vectors, and scalars (real numbers), we can start to consider the operations we can perform on
them. Given a matrix of numbers, one can extend regular scalar algebra (i.e. algebra with real numbers) in a straight forward way.

Scalar addition is simply: m + n = 2 + 5 = 7

Matrix Addition and Subtraction

Addition is similarly defined for matrices. For addition and subtraction, if matrices or vectors are of the same dimension, we
say they are conformable and then they can be added. We will refer to the dimension of a matrix as a specification of the number of
rows and columns the matrix has; so, for the matrix X above we would say X has dimension 2 by 2 or 2 x 2 where the first number
specified is always the number of rows and the second number is the number of columns!

One performs matrix addition element by element. Thus, for a pair of dimension 2 by 2, addition proceeds as follows for the
problem A+B =C

Subtraction similarly follows. It is important to keep in mind that matrix addition and subtraction is only defined if the
matrices are the same dimension. If they do, they are said to be conformable for addition. If not, they are nonconformable.

Here is another example:

There are two important properties of matrix addition that are worth noting:

 A + B = B + A. In other words, matrix addition is commutative.


 (A + B) + C = A + (B + C). In other words, matrix addition is associative.
Transposition and Symmetric Matrices

Another operation that is often useful is transposition. In this operation, the subscripts are exchanged for each element of the
matrix A. Thus, an j x k matrix becomes an k by j matrix. Transposition is denoted by writing a T as a superscript (or sometimes with a
’ mark) on the original matrix name. Here is an example:

There are a couple of results regarding transposition that are important to remember:
 An j by k matrix A is said to be symmetric ⇐⇒ A = AT . This implies, of course, that all symmetric matrices are square.
Here is an example:

 A 
T T
= A . In words, the transpose of the transpose is the original matrix.
 k  A
T
 For a scalar k, = k  AT (kA)_ = kA_
 For two matrices of the same order, it can be shown that the transpose of the sum is equal to the sum of the transposes.
 A  B
T
Symbolically: = AT  BT
 Transposition is also commutative.

Scalar Multiplication

So far we have defined addition and subtraction, as well as transposition. Now we turn our attention to multiplication. The
first type of multiplication is a scalar times a matrix. In words, a scalar α times a matrix A equals the scalar times each element of A.
Thus,

So, for:
Matrix Multiplication

Now we will discuss the process of multiplying two matrices. We apply the following definition of matrix multiplication. Given A of
dimension m by n (i.e. m rows and n columns) and B of dimension n by r, then the product C = AB is a matrix of dimension m x r
matrix whose entries are defined by:

where i = 1, . . .,m and j = 1, . . . , r. Note that for matrices to be multiplication conformable, the number of columns in the first matrix
n must equal the number of rows in the second matrix n.

It is easier to see this by looking at a few examples. Let

We can now define their product. Here we would say that B is pre-multiplied by A, or that A is post-multiplied by B:

Note that A is of order (2, 3), and B is of order (3, 2). Thus, the product AB is of order (2, 2).

We can similarly compute the product BA which will be of order (3, 3). You can verify that this product is:

This demonstrates that the multiplication of matrices is not commutative. In other words: AB != BA.

Given this notation, there are a couple of identities worth noting:


 We have already shown the matrix multiplication is not commutative: AB  BA.
 Matrix multiplication is associative. In other words: (AB)C = A(BC)
 Matrix multiplication is distributive. In other words: A(B + C) = AB + AC
 Scalar multiplication commutative, associative, and distributive.
 AB 
T
 The transpose of a product takes an interesting form, that can easily be proven: = BT AT
In this programming Assignment you will write a class called Matrix that will allow of create and operate with matrices containing
real numbers (represented as doubles).

Method Description
Matrix() Creates an empty Matrix of dimension 0 by 0.
Matrix( int rows, int cols) Creates a Matrix of dimension rows by columns ( rows x cols) in which
all elements are initialized to 0.0.
Matrix( double[][] a) Creates a Matrix of the same dimension as the 2-d array a that contains
the same entries. A new matrix should be created from a rather than simply
using a’s address
public int rows() returns the number of rows in the matrix
public int cols() returns the number of colums in the matrix
public double get( int r, int c) returns the elements (a double) at entry r, c in the matrix. You can
assume that r and c will be valid indices!
public void set( int r, int c, double x) set’s element r,c in the Matrix to the double value x
public Matrix mul( double a ) multiples all elements in Matrix by scalar a and returns a new matrix.
The calling object is not modified.
public Matrix add( Matrix b) Add calling object to matrix b returning a new Matrix c. If the matrices
are not conformable, the method returns null. Note: per the instructions,
array access should be in row-major order (see instructions that follow).
public Matrix sub( Matrix b) Subtracts matrix b from the calling object and returning a new Matrix.
If the two matrices are not conformable, null is returned. Note: per the
instructions, array access should be in column-major order (see instructions
that follow).
publix Matrix mul( Matrix b ) Multiplies the calling object by Matrix b returning a new Matrix
containing the product. If the matrices are not conformable to
multiplication, null is returned.
public Matrix transpose( ) returns the transpose of the calling object as a new Matrix; the calling
object is not changed.
public double trace() returns the trace of the square matrix. The trace is the sum of the elements
on the main diagonal (from the upper left to the lower right element) of
the Matrix. If the matrix is not square, the method is not defined
(assume the matrix will be square when writing this method!)
public static Matrix id( int n ) returns and n x n identity Matrix. If n is not non-negative, returns null.
The identity matrix is a matrix containing zeros in every entry except those
one the main diagonal (i.e. elements from the upper left to the lower right
element) .
For a example,
the 2 x 2 identity matrix is é 1 0 ù
ê ú
ë 0 1 û
the 3 x 3 identity matrix is é 1 0 0 ù
ê ú
ê 0 1 0 ú
ê 0 0 1 ú
ë û
public boolean equals( Matrix b ) returns true or false indicating whether the calling object and matrix b
are equal. If the matrices are not conformable, they are not considered
equal.
public boolean isSymmetric() returns true or false indicating whether the calling object is symmetric
or not. If the matrix is not square, then it can’t be symmetric! See examples
of symmetric matrices in notes.
public String toString() returns a String representation of the form

“| a[0][0] a[0][1] … a[0][cols-1] | \n


| a[1][0] a[1][1] … | \n
| … | \n
| a[rows-1][0] … a[rows-1][cols-1] |”

Complete this assignment in the order outlined on the next page. You will verify your code and the operation of each Part outlined
below.
part I (Basic Class Outline)
1. Begin by creating the Matrix class. A Matrix will be represented as a 2D array of doubles.
Add a single instance variable m for referring to a 2-dimensional array of doubles.
2. Create the three class constructors for the class. Each constructor should initialize the instance variable m appropriately.
3. We will write the class method toString together.
4. Add code to the driver program to test the following operations.
a. In the MatrixDriver class, there are several 2D arrays named with lower case letters, a, b, sq, and sy. In the section labelled
Part I, write code to create four Matrices named A, B, SQ, and SY using a, b, sq, and sy to initialize them.
b. print matrices A and B using the toString method.

Part II
1. Write method rows, cols, get, set, and scalar multiplication method, mul outlined above.
a. discussing using class methods versus direct instance variable referencing.
2. Add code to the driver program to test the following operations.
a. In the section labeled Part II, write a code segment that will create a Matrix named T which contains 3 times the Matrix B
using the mul method.
b. Write a code segment that prints the contents of Matrix T without using the toString method; i.e. use only the new methods
we wrote in this part.
c. Using the get and set methods, change the element in the lower right corner of Matrix T to the value -2.5. Then display the
contents of Matrix T using the toString method. In referring to the element in the lower right corner of the array T pretend
you don’t know the dimensions of the matrix and “ask” matrix T for its dimensions.

Part III
1. Write the static method id that returns the n x n identity matrix, (I from your math class). This method is decribed in the table on the
previous page.
2. Write the add and sub methods. BUT have the add method perform the addition using row-major traversal and sub perform its
operations using a column-major traversal of the matrices. (For these methods the order of traversal does not effect the final answer
(for other operations, I often does) but I want to know that you understand what these two traversals are and how to code them.)
3. Add code to the driver program to test the following operations
a. Declare a variable C and attempt to perform the operation C = A + B. If the operation is successful print the contents of
Matrix C. If the method is not successful, print the message “Addition of Matrices A and B is undefined!”.
b. Declare a variable D and attempt to perform the operation D = SQ + 3*I where I is the 3 x 3 identity matrix. If the
operation is successful print the contents of Matrix D. If the method is not successful, print the message “Addition of
Matrices SQ and 3I is undefined!”.

Part IV
1. Write the trace, equals, and isSymmetric methods.
2. Add code to the driver program to test the following operations
a. Print the trace of matrix SQ.
b. Write a code segment to check whether A = 3*A and print either the message “A and 3A are equal” or “A and 3A are not
equal”
c. Write a code segment to see if Matrix A is symmetric and print either the message “A is symmetric” or “A is not
symmetric”
d. Write a code segment to see if Matrix SQ is symmetric and print either the message “SQ is symmetric” or “SQ is not
symmetric”

Part V
1. Write the transpose, and matrix mul methods
2. Write an alternative isSymmetric method named isSymmetric2 which uses the equals and transpose methods. This will be a
very brief method!
3. Add code to the driver program to demonstrate the following operations:
a. Write a code segment to determine if matrix SQ is symmetric using the isSymmetric2 method. Print a message indicating
whether it is “SQ is Symmetric” or “SQ is Not symmetric”
b. Write a code segment to determine if matrix SY is symmetric using the isSymmetric2 method. Print a message indicating
whether it is “SY is Symmetric” or “SY is Not symmetric”
c. Write a code segment to attempt the multiplication C = AB . If the multiplication is successful, print the product matrix C. If
not display the message “AB is not defined.”
d. Write a code segment to attempt the multiplication C = BA . If the multiplication is successful, print the product matrix C. If
not display the message “BA is not defined.”
Desired Output:

Part I:
| -2.00 1.00 3.00 |
| 4.00 1.00 6.00 |

| 3.00 -2.00 |
| 2.00 4.00 |
| 1.00 -3.00 |

Part II:
9.00 -6.00
6.00 12.00
3.00 -9.00
| 9.00 -6.00 |
| 6.00 12.00 |
| 3.00 -2.50 |

Part III:
Addition of Matrix A and B is undefined!
| 5.00 2.00 3.00 |
| 4.00 9.00 6.00 |
| 7.00 8.00 13.00 |

Part IV:
Trace of SQ is 15.00

Part V:
Matrix SQ is NOT symmetric.
Matrix SY is symmetric.
| -1.00 -1.00 |
| 20.00 -22.00 |

| -14.00 1.00 -3.00 |


| 12.00 6.00 30.00 |
| -14.00 -2.00 -15.00 |

You might also like