Java Array Normalize normalizeMatrix(double[][] M)

Here you can find the source of normalizeMatrix(double[][] M)

Description

Adjusts matrix elements so that sum of all positive elements in each row does not exceed 1.

License

Open Source License

Parameter

Parameter Description
M matrix (2-dimensional array of type <code>double</code>).

Declaration

public static void normalizeMatrix(double[][] M) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/* w ww .  ja  v  a 2s  . co m*/
     * Adjusts matrix elements so that sum of all positive elements in each row
     * does not exceed 1.
     * @param M matrix (2-dimensional array of type <code>double</code>).
     */
    public static void normalizeMatrix(double[][] M) {
        if (M == null)
            return;
        int m = M.length;
        int n = M[0].length;
        for (int i = 0; i < m; i++) {
            boolean hasNegative = false;
            int countNegative = 0;
            int idxNegative = -1;
            double sum = 0.0;
            for (int j = 0; j < n; j++)
                if (M[i][j] < 0) {
                    countNegative++;
                    idxNegative = j;
                    if (countNegative > 1)
                        hasNegative = true;
                } else
                    sum += M[i][j];
            if (countNegative == 1) {
                M[i][idxNegative] = Math.max(0, (1 - sum));
                sum += M[i][idxNegative];
            }
            if ((!hasNegative) && (sum == 0.0)) {
                M[i][0] = 1;
                //for (int j = 0; j < n; j++)
                //M[i][j] = -1;
                continue;
            }
            if ((!hasNegative) && (sum < 1.0)) {
                for (int j = 0; j < n; j++)
                    M[i][j] = (1 / sum) * M[i][j];
                continue;
            }
            if (sum >= 1.0)
                for (int j = 0; j < n; j++)
                    if (M[i][j] < 0)
                        M[i][j] = 0;
                    else
                        M[i][j] = (1 / sum) * M[i][j];
        }
        return;
    }
}

Related

  1. normalizeInnerPointDistanceMax(double[][] distances, double maxDist)
  2. normalizeL2(double[] a)
  3. normalizeL2(double[] histogram)
  4. normalizeLengthInPlace(double[] in)
  5. normalizeLog(double[] logs)
  6. normalizeMatrix(float[] cm)
  7. normalizeMemberNames(final String[] memberNames)
  8. normalizePositiveValues(double[][] array)
  9. normalizeProb(double[] prob)