检查给定矩阵是否具有有效维度 - JAVA

Check if the given Matrix has Valid dimensions - JAVA

我想检查给定的 矩阵 是否具有有效维度。 This Matrix Below Invalid Dim 因为它不满足 Matrix 属性

Matrix x = new Matrix(new double[][]{
                { 1.0, 2.0, 3.0},
                { 4.0, 5.0 }
        }) 

我尝试了几种方法,最新的是:

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (array[i][j] = null) {
                    throw new InvalidDimensionsException("Invalid Dim");
                }
            }
        }

只是它不是null,它只是没有元素而已! 不幸的是,没有任何效果,我 运行 失去了想法。

我很乐意听取您的建议

提前致谢

如果您知道矩阵必须具有的列数,则可以检查其中每个一维数组的大小。

double[][] mat = ...; //get the underlying array from the matrix
for (double[] arr : mat) if (arr.length != numCols) throw new InvalidDimensionsException(...);

否则,您可以取第一行的大小并检查所有行的长度是否相同。

//If it's empty, there's no point checking further
if (mat.length != 0) {
  //All the rows should have this same length
  int numCols = mat[0].length;
  for (int i = 1; i < mat.length; i ++)
    if (mat[i].length != numCols) throw new InvalidDimensionsException(...);
}

double[][]的单元格不能为空,所以问题中的代码是没有意义的,特别是因为它不能编译(=应该是==)。

要验证二维数组是否为矩形,即有效矩阵,请这样做:

double[][] matrix = {
        { 1.0, 2.0, 3.0},
        { 4.0, 5.0 }
};
int height = matrix.length;
if (height == 0)
    throw new InvalidDimensionsException("Invalid Dim");
int width = matrix[0].length;
if (width == 0)
    throw new InvalidDimensionsException("Invalid Dim");
for (int y = 1; y < height; y++)
    if (matrix[y].length != width)
        throw new InvalidDimensionsException("Invalid Dim");

代码将抛出 NullPointerException 是任何数组 null.