inverse Matrix - Android java.lang

Android examples for java.lang:Math Matrix

Description

inverse Matrix

Demo Code


//package com.java2s;

public class Main {
    public static float[][] inverseMatrix(float[][] m) {
        int size = m.length;
        float[][] result = new float[size][size];
        float buf; // temporary data

        // make identity matrix
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                result[i][j] = (i == j) ? 1.f : 0.f;
            }/*  w ww .j a  v a 2 s .  co  m*/
        }

        // sweep out
        for (int i = 0; i < size; i++) {
            // exception for division by zero
            if (m[i][i] == 0.f)
                return null;

            buf = 1 / m[i][i];
            for (int j = 0; j < size; j++) {
                m[i][j] *= buf;
                result[i][j] *= buf;
            }
            for (int j = 0; j < size; j++) {
                if (i != j) {
                    buf = m[j][i];
                    for (int k = 0; k < size; k++) {
                        m[j][k] -= m[i][k] * buf;
                        result[j][k] -= result[i][k] * buf;
                    }
                }
            }
        }

        return result;
    }
}

Related Tutorials