Articles » Languages » Java » General » Revisions

Article

# Matrix operations in Java

By , 11 Dec 2012
 Rate this:
This is an old version of the currently published article.

## Introduction

This article introduces some basic methods in Java for matrix additions, multiplications, inverse, transpose, and other relevant operations. The matrix operations are explained briefly and external links are given for more details. The main functions are given as static utility methods. All methods in this article are unit tested and the test codes are part of the attached files.

## Using the code

Matrix is a two dimensional array of numbers. I define Matrix in Java using three parameters; i.e., number of rows (nrows), number of columns (ncols), and the data as an array of `double`s.

```public class Matrix {

private int nrows;
private int ncols;
private double[][] data;

public Matrix(double[][] dat) {
this.data = dat;
this.nrows = dat.length;
this.ncols = dat[0].length;
}

public Matrix(int nrow, int ncol) {
this.nrows = nrow;
this.ncols = ncol;
data = new double[nrow][ncol];
}```

Matrices are fundamental in mathematics and their operations are vital in quantitative subjects. In separate articles, I will use these functions for statistical modeling.

Transpose

Transpose of a matrix is produced by swapping the rows with columns.

```public static Matrix transpose(Matrix matrix) {
Matrix transposedMatrix = new Matrix(matrix.getNcols(), matrix.getNrows());
for (int i=0;i<matrix.getNrows();i++) {
for (int j=0;j<matrix.getNcols();j++) {
transposedMatrix.setValueAt(j, i, matrix.getValueAt(i, j));
}
}
return transposedMatrix;
}```

Determinant of a square matrix

A square matrix has an equal number of rows and columns. For these matrices the following method can be used to calculate the determinant. We will use this function later in this article to find the inverse of a matrix.

```public static double determinant(Matrix matrix) throws NoSquareException {
if (!matrix.isSquare())
throw new NoSquareException("matrix need to be square.");

if (matrix.size()==2) {
return (matrix.getValueAt(0, 0) * matrix.getValueAt(1, 1)) - ( matrix.getValueAt(0, 1) * matrix.getValueAt(1, 0));
}
double sum = 0.0;
for (int i=0; i<matrix.getNcols(); i++) {
sum += sign(i) * matrix.getValueAt(0, i) * determinant(createSubMatrix(matrix, 0, i));
}
return sum;
}```

`sign(i)` is a method that returns 1 if i is even and -1 otherwise. More information about determinants are given in http://en.wikipedia.org/wiki/Determinant.

The above method is a recursive function that breaks the larger matrix into smaller ones using the `createSubMatrix` method given below:

```public static Matrix createSubMatrix(Matrix matrix, int excluding_row, int excluding_col) {
Matrix mat = new Matrix(matrix.getNrows()-1, matrix.getNcols()-1);
int r = -1;
for (int i=0;i<matrix.getNrows();i++) {
if (i==excluding_row)
continue;
r++;
int c = -1;
for (int j=0;j<matrix.getNcols();j++) {
if (j==excluding_col)
continue;
mat.setValueAt(r, ++c, matrix.getValueAt(i, j));
}
}
return mat;
}```

The input parameters for this method are the original matrix and the row and column index numbers that need to be deleted from the original matrix to create the sub-matrix.

Cofactor of a matrix

The cofactor of a matrix A is matrix C that the value of element Cij equals the determinant of a matrix created by removing row i and column j from matrix A. Here is the method that calculates the cofactor matrix:

```public static Matrix cofactor(Matrix matrix) throws NoSquareException {
Matrix mat = new Matrix(matrix.getNrows(), matrix.getNcols());
for (int i=0;i<matrix.getNrows();i++) {
for (int j=0; j<matrix.getNcols();j++) {
mat.setValueAt(i, j, sign(i) * sign(j) * determinant(createSubMatrix(matrix, i, j)));
}
}

return mat;
}```

This method is necessary to calculate the inverse of a matrix given in the next section. For details about cofactor, visit http://en.wikipedia.org/wiki/Matrix_of_cofactors#Matrix_of_cofactors.

#### Inverse of a matrix

Inverse of a square matrix A is the matrix A-1 where AA-1=I. I is the identity matrix (see http://en.wikipedia.org/wiki/Inverse_of_a_matrix for more details).

```public static Matrix inverse(Matrix matrix) throws NoSquareException {
return (transpose(cofactor(matrix)).multiplyByConstant(1.0/determinant(matrix)));
}```

In this method the inverse of a matrix is calculated by finding the transpose of the cofactor of that matrix divided by the determinant of that matrix. Not all of square matrices have inverse. If the matrix is not invertible (a singular matrix), the value of the matrix coming out of the above method will be NAN (stands for not a number) or Infinity.

For matrix multiplication, addition, and subtraction, see the attached codes.

## Points of Interest

All of the above operations are fundamental in linear algebra and perhaps the inverse of a matrix is the hardest operation among others to understand and implement.

## History

This is the first version (v1.0.0).

Software Developer (Senior) Investment Bank
United Kingdom
I have a PhD in computational chemistry from Newcastle University. I worked for Imperial College London as research scientist for more than 6 years before joining HSBC, Standard Bank and recently BlackRock as software developer.

Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.

 First Prev Next
 Possible copy of your work??? Member 9540478 8-Dec-13 18:38
 Without constructor [modified] 12blackmaster 24-May-13 4:05
 Re: Without constructor Ata Amini 29-May-13 7:19
 When determinant equals to zero Daemon025 14-Apr-13 0:54
 Re: When determinant equals to zero Ata Amini 14-Apr-13 12:01
 Thanks.. Jayanta Chatterjee 18-Mar-13 5:22
 Determinant of 1x1 matrix leducquang 16-Mar-13 22:37
 Re: Determinant of 1x1 matrix Ata Amini 16-Mar-13 23:00
 Print the whole matrix Member 9908927 13-Mar-13 11:15
 Re: Print the whole matrix Ata Amini 13-Mar-13 12:01
 My vote of 5 naoufelabs 4-Jan-13 10:05
 using libraries Srini Sydney 27-Dec-12 11:58
 Re: using libraries Ata Amini 27-Dec-12 12:20
 Re: Misleading Ata Amini 26-Dec-12 10:13
 Suggestion César de Souza 26-Dec-12 4:49
 Re: Suggestion Ata Amini 26-Dec-12 9:45
 Nice, but... Matt T Heffron 11-Dec-12 7:40
 Re: Nice, but... Ata Amini 26-Dec-12 9:41
 Last Visit: 31-Dec-99 18:00     Last Update: 16-Mar-14 10:42 Refresh 1