90 likes | 476 Views
Multi-dimensional arrays. Allows you to work with matrices int array[][] = new int[20][30] First dimension is number of rows Second dimension is number of columns Can have more than two dimensions Allocated row-pointer in memory A row can be stored anywhere in memory
E N D
Multi-dimensional arrays • Allows you to work with matrices int array[][] = new int[20][30] • First dimension is number of rows • Second dimension is number of columns • Can have more than two dimensions • Allocated row-pointer in memory • A row can be stored anywhere in memory • Elements in a row are stored contiguously • Can visualize as array of arrays
Transpose class transpose { public static void main(String args[]) { int i, j; int table[][] = new int[3][4]; int ttable[][] = new int[4][3]; for(i=0; i < 3; ++i) { for(j=0; j < 4; ++j) { table[i][j] = (i*4)+j+1; System.out.print(table[i][j] + " "); } System.out.println(); } System.out.println(); for(j=0; j < 4; ++j) { for(i=0; i < 3; ++i) { ttable[j][i] = table[i][j]; System.out.print(ttable[j][i] + " "); } System.out.println(); } } }
Matrix multiplication class MatrixMultiply { public static void main (String arg[]) { int m = 20, n = 30, p = 40; double A[][] = new double[m][n]; double B[][] = new double[n][p]; double C[][]; InitializeArray (A, m, n); InitializeArray (B, n, p); C = Multiply (A, B, m, n, p); } // continued in next slide
Matrix multiplication public static void InitializeArray (double x[][], int m, int n) { int i, j; for (i=0;i<m;i++) { for (j=0;j<n;j++) { x[i][j] = i+j; } } }
Matrix multiplication public static double[][] Multiply (double x[][], double y[][], int p, int q, int r) { double z[][] = new double[p][r]; int i, j, k; for (i=0;i<p;i++) { for (j=0;j<r;j++) { z[i][j] = 0; for (k=0;k<q;k++) { z[i][j] += (x[i][k]*y[k][j]); } } } return z; } } // end class
Allocating a triangular matrix • May save memory for symmetric matrices • Allocate space to store the starting addresses of m rows • Then allocate the m rows themselves int m = 20; double[] triangle[] = new double[m][]; int i; for (i=0;i<m;i++) { // allocate lower triangle triangle[i] = new double[i+1]; }
arraylength class arraylength { public static void main(String args[]) { int list[] = new int[10]; int nums[] = { 1, 2, 3 }; int table[][] = { // a variable-length table {1, 2, 3}, {4, 5}, {6, 7, 8, 9} };
System.out.println("length of list is " + list.length); System.out.println("length of nums is " + nums.length); System.out.println("length of table is " + table.length); System.out.println("length of table[0] is " + table[0].length); System.out.println("length of table[1] is " + table[1].length); System.out.println("length of table[2] is " + table[2].length); System.out.println();
// use length to initialize list for(int i=0; i < list.length; i++) list[i] = i * i; System.out.print("Here is list: "); // now use length to display list for(int i=0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); } }