【问题标题】:Calculate no of elements in a matrix计算矩阵中的元素个数
【发布时间】:2017-03-22 01:00:16
【问题描述】:

我正在解决编程中的一个问题,我有一个矩阵并给定两个位置,我需要找到其中的元素,包括给定的元素

例如,一个 1000 行 1000 列的矩阵,初始位置为 [499,499],最终位置为 [500,500],元素数为 4

我想知道是否有任何数学公式可以应用于任何矩阵

【问题讨论】:

  • 编程过程与数学公式并不是一回事。形式上的区别在于编程过程包含 if 语句,而数学公式不包含。您可以轻松地将矩阵的子集转移到另一个较小的矩阵,具体细节因语言而异。

标签: math matrix


【解决方案1】:

要获得元素的数量,它将是 (500-499+1)*(500-499+1)(x2-x1+1)*(y2-y1+1),这可用于可能的内存分配,具体取决于您使用的编程语言。然后要访问矩阵的元素,您可以创建一个使用提供的值计算大小的矩阵并将其返回。

Matrix getSubMatrix(Matrix matrix, int x1, int y1, int x2, int y2) {
    // This is assuming matrixes can be created this way
    // x2-x1+1 and y2-y1+1 should provide the correct dimensions for the values
    // to be extracted from the provided matrix
    Matrix submatrix = new Matrix(x2-x1+1, y2-y1+1);

    // Now we will itterate through both dimensions of the original matrix
    // and the new matrix
    for (int i = 0; i < x2-x1+1; i++) {
        for (int j = 0; j < y2-y1+1; j++) {
            // The new matrix can be accessed with i and j, but the original matrix
            // requires the offset of x1 and y1
            subMatrix[i][j] = matrix[i+x1][j+y1];
        }
    }
    return submatrix;
}

请注意,您也可以使用数组而不是对象作为输入参数和返回值。正如matt 对他的回答所做的那样

正如SergGr 指出的情况,x1 &gt; x2y1 &gt; y2 可以解决该问题,而不是假设x1 &lt; x2y1 &lt; y2。您可以将方法中的x1 替换为min(x1,x2),将x2 替换为max(x1,x2)y1 and y2 也一样。

【讨论】:

  • 我认为您也应该涵盖x1 &lt; x2y1 &gt; y2 的情况,您当前的元素总数公式和代码处理不好。
  • 如果我有一个 3 x 3 的矩阵并输入参数 a[1][3]、a[3][3],则公式看起来不正确。答案应该是 7 个元素,但通过这个计算,我只得到 3 个
  • [ [1,1] , [2,1] , [3,1] ; [1,2] , [2,2] , [3,2] ; [1,3] , [2,3] , [3,3] ] 根据您的规范,它只打印最后一个索引为 3 的元素,因为我们将原始矩阵分割成所有元素的子矩阵,其中第一个索引来自 1 to 3 3 的第二个索引。子矩阵总共包含 3 个元素。
【解决方案2】:

当然,只需使用两个 for 循环即可:

int[][] matrix = new int[1000][1000];
populateMatrix(matrix); // populate the matrix with some values, somehow

int pos_1_X = 499;
int pos_1_Y = 499;
int pos_2_X = 500;
int pos_2_Y = 500;

int numElements = 0;

for(int x = pos_1_X; x <= pos_2_X; x++) {
    for(int y = pos_1_Y; y <= pos_2_Y; y++) {
        numElements++; // increment the counter
        System.out.printf("matrix[%d][%d] = %d", x, y, matrix[x][y]); // print the element
    }
}

System.out.println("Number of elements: " + numElements);

【讨论】:

  • 我很清楚我不是在寻找编程解决方案,我想知道是否有一个数学表达式可以用于在任何给定矩阵上计算它。
  • 我不知道如何回答你的问题对不起。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 2016-07-03
  • 1970-01-01
  • 2021-04-29
  • 2011-02-22
相关资源
最近更新 更多