# 3D Matrix subtract from 2D

Discussion in 'Mac Programming' started by narvin, May 29, 2016.

Tags:
1. May 29, 2016
Last edited by a moderator: May 29, 2016

### narvin macrumors newbie

Joined:
May 28, 2016
Location:
Uk
#1
I have the code bellow , which is for subtracting the 3D matrix from 2D.
Code:
```import java.util.*;
class test28{

public static void main ( String[] args ) {

int [][][] arr1 = {{{6,3,9,0},{8,6,5,3},{5, 4, 6, 7}}};

int [][] arr2= {{6,3,5,0},{8,6,5,3}};

test28 test = new test28();

System.out.println(Arrays.deepToString(test.subtract(arr1,arr2)));

}
public static int [][] subtract(int[][][] a, int[][] b)  {
int[][] diff = new int[a[0].length][a[0][0].length];
for ( int j=0; j<a[0].length; j++){
for ( int k=0; k<a[0][0].length; k++){

diff[j][k] = a[0][j][k]- b[j][k];
}
}
return diff;
}
}
*************************************************************************************```
Iam receiving error which is IndexOutOfBound

2. ### chown33 macrumors 604

Joined:
Aug 9, 2009
Location:
Sailing beyond the sunset
#2
"Two matrices must have an equal number of rows and columns to be added."​

Do your matrices meet this requirement?

Code:
```int [][] arr2 = {
{6,3,5,0},  // row 0, has 4 columns
{8,6,5,3}  // row 1, has 4 columns
};  // 2 rows total, 4 columns total```
If you think your code doesn't meet the requirement, then figure out what to change and where, so the matrices are subtractable.

3. ### Amazing Iceman macrumors 68040

Joined:
Nov 8, 2008
Location:
Florida, U.S.A.
#3
I think the problem is that you are using .length instead of .count in your for-loops, as in here:

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

Same may go to the other loop.
To be sure, use NSLog to output the value of j to the Console.

4. ### dylanryan macrumors member

Joined:
Aug 21, 2011
#4
This is clearly Java code, not Objective C, so length is the correct way to see how large an array is.

That said, you are iterating over the wrong length. Looking at the code, here are some lengths that I would expect:

arr1.length => 1
arr1[0].length => 3
arr1[0][0].length => 4

arr2.length => 2
arr2[0].length => 4

Now, lets take this loop, and see what happens at the extreme cases

Code:
``` for ( int j=0; j<a[0].length; j++){
for ( int k=0; k<a[0][0].length; k++){

diff[j][k] = a[0][j][k]- b[j][k];
}```

So, j will go up to 2 at the largest (and k will go up to 3).
So, when j=2, then we try to access arr2[2][k], but arr2's length is 2, so the only valid indices are 0 and 1. There is no 2, hence the index out of bounds exception

Incidentally, I am not sure why arr1 is a 3D array. You only need 2 dimensions to store a matrix, no matter how many dimensions there are in the matrix. A 50-dimentional matrix fits comfortably in a 2D array.

5. ### Amazing Iceman macrumors 68040

Joined:
Nov 8, 2008
Location:
Florida, U.S.A.
#5
My bad, i wasn't paying too much attention. I thought it was Objective-C.