You are on page 1of 2

Vectors and Matrices

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. Note: that the Java core language includes a class called Vector in its java.util package (packages are Java class libraries and are discussed in Chapter 5). However, this is a container class that provides for adding new elements, removing elements, etc. It is quite useful but is fairly slow and not intended for mathematical operations.

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}; double [] vec2 = {1.0,0.0,0.2};

We then need methods to carry out various vector operations such as the dot products:
double dot (double [] a, double [] b) { double scaler = 0.0; for( int i=0; i < a.length; i++) { scaler += a[i]*b[i]; } return scaler; }

(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 matrices is to use arrays with two indices:
double [][] dMatrix = new double[n][m];

However, this is not a true 2 dimensional array in memory 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 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 multidimensional array.
public class Matrix2D { private final double[] fMat; private final int fCols; private final int fRows; private final int fCcol; private final int fRow; public Matrix2D (int rows, int cols ) { fCols = cols; fRows = rows; fMat = new double[rows * cols]; } /** r = row number, c = column number **/ public double get (int c, int r) { return fMat[r * fCols + c]; } /** r = row number, c = column number **/ public double set (int c, int r, double val) { fMat[r * fCols + c] = val; }

...other methods, e.g. to fill the array, access a subset of elements, etc.
}

You might also like