|
|||||||||||
|
Vector and matrix operations are obviously standard tools throughout science and engineering. Here we will look at some ways to use Java arrays to represent and carry out operations for vectors and matrices.
Vectors The elements of a floating point array can represent the component values of a vector, as in double
[] vec1 = {0.5,0.5,0.5}; We then need methods to carry out various vector operations such as the dot products: double
dot (double
[] a, double
[] b) { (Note that a more robust method would check that the vector arguments were non-null and the array lengths were equal.) Problem: Create a class with dot and cross product static methods. Matrices The obvious approach for matices is to use arrays with two indices: double [][] dMatrix = new double[n][m]; However, this is not a true 2 dimensional array in memeory but is actually a 1-D array of references to other 1-D arrays. In other languages such as C & C++, moving from one element to the next in a 2-D array involves simple incrementing of a memory pointer. The multiple referencing in a Java 2 dimensional array, on the other hand, causes a performance penalty, especially if the matrix is used in intensive calculations. One approach (ref) to ameliorate this problem to some extent is to use a 1-D array. The code below shows how one might develop a matrix class to use a 1-D array for 2-D operations. A sophisticated compiler can optimize such a class and in some cases provide better performance than a multi-dimensional array.
Latest update: Oct. 20, 2004 |
|
|||||||||
|