10 likes | 124 Views
CS315 Extra credit: The array mapping function for a lower triangular matrix . 0.1 1.2 2.3 3.4 4.5 5.6 6.7 7.8 8.9 9.0 .
E N D
CS315 Extra credit: The array mapping function for a lower triangular matrix 0.1 1.2 2.3 3.4 4.5 5.6 6.7 7.8 8.9 9.0 Triangular matrices show up quite often in various math, science, or engineering problems. The figure above illustrates an example of a lower triangular 4x4 matrix of floating point numbers, M. A lower triangular matrix is the lower half below the diagonal of a square matrix of size n x n Sometimes, as shown here, it includes the diagonal; sometimes it doesn’t; depends on the application. The unused (upper) entries in the triangular matrix may either be some constant value (often 0) or just symmetric (i.e., Mi,j = Mj,i), depending on the specific context . The obvious way to represent a 2-dimensional matrix in C is as a 2-dimensional array, e.g., floatM[n][n], but if the matrix is triangular, that wastes almost half the space needed by C to store the array − all the upper half entries, M[i][j], where j>i, being unnecessary. A space saving implementation for such triangular matrices is to declare a 1-dimensional array named something else, say x, and lay out the contents of M in x in it row by row, like so: array xin memory: 0.1 1.2 2.3 3.4 4.5 5.6 6.7 7.8 8.9 9.0… x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7] x[8] x[9] … Now the problem is, of course, that what the programmer wants to write for clarity, e.g., M[i][j], won’t work, since there is no longer a 2-dimensional array named M. The values for the matrix M are stored in the 1-dimensional array named x. So the programmer needs to write a functionnamed M such that the function call M(2,1) would find and return the correct M2,1 value of 4.5 from the 1-dimensional array named x. To correctly return the Mi,j value, the function M will have to hash its arguments, 2-tuples of the form <i,j>, into an index k into the 1-dimensional array named xso it can find the correct x[k] containing Mi,j. That (perfect) hash function is known as the array mapping function for a lower triangular matrix implemented inside a 1-dimensional array. For a lower triangular matrix that includes the diagonal, as illustrated above, what is that hash function as a function of i ,j, andn, where n x n is the size of the original (square) matrix,? I.e., given i and j, where is Mi,j stored in x? What is the hash function if the diagonal is not included i.e., there’s no useful information stored there?