Click here to Skip to main content
13,589,335 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


31 bookmarked
Posted 16 Jun 2012
Licenced CPOL

Matrix Operations in Java

, 21 Mar 2013
Rate this:
Please Sign up or sign in to vote.
A set of static methods in Java that are critical in all mathematical calculations that involve matrices


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.

As suggested by a member (i.e., César de Souza), the matrix decomposition methods such as Cholesky Decomposition and LU decomposition are more common in matrix operations.

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 doubles.

public class Matrix {

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

    public Matrix(double[][] dat) { = 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 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;

For more information about transpose of a matrix, visit this link.

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() == 1) {
	return matrix.getValueAt(0, 0);
    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 += changeSign(i) * matrix.getValueAt(0, i) * determinant(createSubMatrix(matrix, 0, i));
    return sum;

changeSign(i) is a method that returns 1 if i is even and -1 otherwise. More information about determinants are given here.

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)
            int c = -1;
        for (int j=0;j<matrix.getNcols();j++) {
            if (j==excluding_col)
            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, changeSign(i) * changeSign(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 this link.

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 this link 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 code.

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.


This is the first version (v1.0.2).


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ata Amini
Software Developer (Senior) Private
United Kingdom United Kingdom
I have a PhD in computational chemistry from Newcastle University. I worked for Imperial College London as research scientist for 6.5 years followed by 7 years in banking in the City of London as senior software developer. Currently I do mathematical modelling and software development for a private company and spend some time in research and development in the University of Newcastle.

You may also be interested in...

Comments and Discussions

QuestionInverse Matrix Pin
Member 1233635018-Feb-16 4:30
memberMember 1233635018-Feb-16 4:30 
AnswerRe: Inverse Matrix Pin
Ata Amini15-Mar-16 21:26
memberAta Amini15-Mar-16 21:26 
Generalthanksgiving Pin
st3car21-Jun-15 9:34
memberst3car21-Jun-15 9:34 
QuestionPossible copy of your work??? Pin
Member 95404788-Dec-13 18:38
memberMember 95404788-Dec-13 18:38 
AnswerRe: Possible copy of your work??? Pin
Ata Amini12-Mar-15 2:24
memberAta Amini12-Mar-15 2:24 
QuestionWithout constructor Pin
12blackmaster24-May-13 4:05
member12blackmaster24-May-13 4:05 
AnswerRe: Without constructor Pin
Ata Amini29-May-13 7:19
memberAta Amini29-May-13 7:19 
QuestionWhen determinant equals to zero Pin
Daemon02514-Apr-13 0:54
memberDaemon02514-Apr-13 0:54 
AnswerRe: When determinant equals to zero Pin
Ata Amini14-Apr-13 12:01
memberAta Amini14-Apr-13 12:01 
GeneralThanks.. Pin
Jayanta Chatterjee18-Mar-13 5:22
memberJayanta Chatterjee18-Mar-13 5:22 
BugDeterminant of 1x1 matrix Pin
leducquang16-Mar-13 22:37
memberleducquang16-Mar-13 22:37 
GeneralRe: Determinant of 1x1 matrix Pin
Ata Amini16-Mar-13 23:00
memberAta Amini16-Mar-13 23:00 
QuestionPrint the whole matrix Pin
Member 990892713-Mar-13 11:15
memberMember 990892713-Mar-13 11:15 
AnswerRe: Print the whole matrix Pin
Ata Amini13-Mar-13 12:01
memberAta Amini13-Mar-13 12:01 
GeneralMy vote of 5 Pin
naoufelabs4-Jan-13 10:05
membernaoufelabs4-Jan-13 10:05 
Very helpful.
Good program, easy to understand
Questionusing libraries Pin
Srini Sydney27-Dec-12 11:58
memberSrini Sydney27-Dec-12 11:58 
AnswerRe: using libraries Pin
Ata Amini27-Dec-12 12:20
memberAta Amini27-Dec-12 12:20 
QuestionMisleading Pin
Florian Rappl26-Dec-12 7:23
memberFlorian Rappl26-Dec-12 7:23 
AnswerRe: Misleading Pin
Ata Amini26-Dec-12 10:13
memberAta Amini26-Dec-12 10:13 
SuggestionSuggestion Pin
César de Souza26-Dec-12 4:49
memberCésar de Souza26-Dec-12 4:49 
GeneralRe: Suggestion Pin
Ata Amini26-Dec-12 9:45
memberAta Amini26-Dec-12 9:45 
SuggestionNice, but... Pin
Matt T Heffron11-Dec-12 7:40
memberMatt T Heffron11-Dec-12 7:40 
GeneralRe: Nice, but... Pin
Ata Amini26-Dec-12 9:41
memberAta Amini26-Dec-12 9:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.180615.1 | Last Updated 21 Mar 2013
Article Copyright 2012 by Ata Amini
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid