How to grab only a certain row of a two-dimensional matrix in java?

Question

When I have a two-dimensional matrix in java, but I only want to work with a certain row of that matrix respectively creating a new array that contains the contents of the matrix in that certain row, how would I accomplish that (with primitives)?

So, for example, we would write:

int[][] matrix = new int[10][10];

Now we have a two-dimensional matrix with 10 rows and 10 columns. Assume that we fill the whole matrix with certain elements, and now, I wish to work only with the first row, meaning to define a new array that contains exactly the elements of the first row of the matrix.


Show source
| java   | arrays   | matrix   2016-12-21 17:12 1 Answers

Answers to How to grab only a certain row of a two-dimensional matrix in java? ( 1 )

  1. 2016-12-21 17:12

    Assuming that row means the horizontal segments of the matrix (as it almost always is):

    In a 2 dimensional array in java, the rows are the first index and the columns are the second index.
    Basically a two dimensional array is an array of arrays. So

    int[][] intArray = new int[10][3];
    

    is actually an array of size 10. Each element in the array is an array in itself of size 3.

    Say you have an array of integers

    int[][] integerArray; //we have to initialize the array.
    

    then we want to work with the 1st row. We would use:

    int[] arr = integerArray[0];
    

    LIMITATIONS

    1. The matrix must be initialized (must have values in cells)
    2. The matrix must have a 1st row

    Note: we use integerArray[0] because arrays start at index 0, so the third row would be integerArray[2]

Leave a reply to - How to grab only a certain row of a two-dimensional matrix in java?

◀ Go back