Multidimensional Arrays Instructor Mainak Chaudhuri mainakccse iitk ac

  • Slides: 7
Download presentation
Multi-dimensional Arrays Instructor: Mainak Chaudhuri mainakc@cse. iitk. ac. in 1

Multi-dimensional Arrays Instructor: Mainak Chaudhuri mainakc@cse. iitk. ac. in 1

Announcements • For project ideas access last semesters’ course pages • Submit a half-page

Announcements • For project ideas access last semesters’ course pages • Submit a half-page proposal by 10 th October – Problem statement – Approach • Progress report by 1 st November (two pages) • Final report and demo in the last week of class 2

Multi-dimensional arrays • Allows you to work with matrices int array[][] = new int[20][30]

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 3

Matrix multiplication class Matrix. Multiply { public static void main (String arg[]) { int

Matrix multiplication class Matrix. Multiply { 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[][]; Initialize. Array (A, m, n); Initialize. Array (B, n, p); C = Multiply (A, B, m, n, p); } // continued in next slide 4

Matrix multiplication public static void Initialize. Array (double x[][], int m, int n) {

Matrix multiplication public static void Initialize. Array (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; } } } 5

Matrix multiplication public static double[][] Multiply (double x[][], double y[][], int p, int q,

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; } 6 } // end class

Allocating a triangular matrix • May save memory for symmetric matrices • Allocate space

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[i] = new double[i+1]; } 7