Next: Expressions that denote matrix Up: Unit 07 Previous: The class ApartmentOwner: realization

## Matrices

A matrix is a collection of elements of the same type, organized in the form of a table. Each element is indexed by a pair of numbers that identify the row and the column of the element.

A matrix can be represented in Java through an array, whose elements are themselves (references to) arrays representing the various rows of the matrix.

Declaration of a matrix

A matrix is declared in the following way (as an array of arrays):

```int[][] m;   // declaration of an array of arrays (matrix) m
```

Creation of a matrix

As for arrays, before a matrix can be used, it must be created.

Example: Creation of a 3x5 matrix accessible through the variable m:

```// creation of an array object of 3 elements,
// each of which will contain the reference to a row of the matrix
m = new int[3][];

m[0] = new int[5];  // creation of row 0 of the matrix (5 columns)
m[1] = new int[5];  // creation of row 1 of the matrix (5 columns)
m[2] = new int[5];  // creation of row 2 of the matrix (5 columns)
```

Note that, by creating the rows one at a time, it is also possible to have rows with different dimensions. This would correspond to a matrix with an irregular shape (as opposed to a rectangular matrix).

In Java, there is an equivalent, more compact way of creating a rectangular matrix, without having to construct the rows one at a time:

```// creation of an array object of 3 elements,
// each of which is an array of 5 integers (3x5 matrix)
m = new int [3][5];
```

Note that, in this way, all rows of the matrix necessarily have the same number of elements.

The single elements of the matrix can be treated like ordinary variables of the corresponding type. To access them, we have to specify the index of the row and the index of the column of the element.

Example:

```// assignment of a value to the element of m in row 1, column 2
m[1][2] = 39;

// assignment of a value to the element of m in row 0, column 0
m[0][0] = 44;

// access to the element of m in row 1, column 2
System.out.println(m[1][2]);   // prints out 39
```

Next: Expressions that denote matrix Up: Unit 07 Previous: The class ApartmentOwner: realization