0

Okay so I wrote this code with my friend's help to "remove the row" of a matrix, but I don't really understand whats going on with the "for" , can someone explain to me why it's done that way?

Edit: Okay so what i don't understand is the way that both loops are working

public static double [][] removeRow(double [][] m , int n){                             

    double [][] finalm = new double [m.length-1][m[0].length];  

    for (int i = 0; i<finalm.length; i++) {                     

        for (int j = 0; j<finalm[i].length; j++) {              

                if (i<n) {                                      
                    finalm[i][j]=m[i][j];                       
                }
                if (i>=n) {                                     
                    finalm[i][j]=m[i+1][j];                     
                }
            }
        }

    return finalm;
}

public static void main(String[] args) {

    double [][] m = {{1,2,3},{1,9,2},{0,6,3}};
    double [][] result = removeRow(m,0);

    for (int i = 0; i<result.length; i++) {

        for (int j = 0; j<result[i].length; j++) {
            System.out.println(result[i][j]);
                }
            }
        }
}
  • 5
    I would recommend running this through the dubugger so you can see what is happening – GBlodgett Dec 10 '18 at 19:01
  • It sounds like you're asking how a `for` loop works - Possible duplicate of [How does the for loop exactly work out](https://stackoverflow.com/questions/25345748/how-does-the-for-loop-exactly-work-out) – Krease Dec 10 '18 at 19:03
  • What i dont understand is how a loop inside the other works, like which order is followed – Juan Hernández Dec 10 '18 at 19:10

1 Answers1

4

Picture the Array:

0, 0, 0, 0
1, 1, 1, 1
2, 2, 2, 2   <----- n
3, 3, 3, 3

Where n is 2.

The method constructs an empty Array with one less row:

0, 0, 0, 0
0, 0, 0, 0
0, 0, 0, 0

Then it loops for each loop, and if the index is less than n, then it copies it to the second Array. So rows one and two will be copied:

0, 0, 0, 0
1, 1, 1, 1
0, 0, 0, 0

Then if the index is equal to or more than n, it will copy the row from index + 1 to the second Array:

//Skips the row 2, 2, 2, 2
0, 0, 0, 0
1, 1, 1, 1
3, 3, 3, 3

Also note that the inner loop is not necessary since we are copying entire rows. We can simply do:

public static double [][] removeRow(double [][] m , int n){ 
    double [][] finalm = new double [m.length-1][m[0].length];  

    for (int i = 0; i<finalm.length; i++) {                     
          if (i<n) {                                      
              finalm[i]=m[i];                       
          }
          if (i>=n) {                                     
              finalm[i]=m[i+1];                     
          }
    }
    return finalm;
}
GBlodgett
  • 12,704
  • 4
  • 31
  • 45