Here you can find the source of normalizeMatrix(double[][] M)
Parameter | Description |
---|---|
M | matrix (2-dimensional array of type <code>double</code>). |
public static void normalizeMatrix(double[][] M)
//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; } }