developer2015
developer2015

Reputation: 423

Calculate no of elements in a matrix

I am solving a problem in programming where I have a matrix and given two positions I need to find the elements in between including the elements given

So for example a matrix with 1000 rows and 1000 columns initial position is [499,499] and final position is [500,500] the number of elements are 4

I wanted to know if there is any mathematical formula that can be applied on any matrix

Upvotes: 1

Views: 152

Answers (2)

avlec
avlec

Reputation: 394

Well to get the number of elements it would be (500-499+1)*(500-499+1) or (x2-x1+1)*(y2-y1+1) which could be used for possible memory allocation depending on what programming language you are using. Then to access the elements of the matrix, you could create a matrix of size calculated with the values provided and return that.

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;
}

Note that you could also use arrays instead of Objects for the input parameters and return value. As matt did with his answer

As SergGr pointed out the case where x1 > x2 or y1 > y2 to fix that and not assume that x1 < x2 and y1 < y2. You can replace the x1 in the method with min(x1,x2), x2 with max(x1,x2) and the same for y1 and y2.

Upvotes: 1

Matt
Matt

Reputation: 3760

Sure just do it with two for loops:

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);

Upvotes: 0

Related Questions