July 28, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Working with Column Matrices, Points, and Vectors: Math for Java Game Programmers

  • May 6, 2008
  • By Richard G. Baldwin
  • Send Email »
  • More Articles »

Java Programming Notes # 1704


Preface

General

Third in a series

This tutorial is the third in a series designed to teach you some of the mathematical skills that you will need (in addition to good programming skills) to become a successful game programmer. The first lesson was titled Math for Java Game Programmers, Getting Started. The previous lesson was titled Math for Java Game Programmers, Updating the Math Library for Graphics (see Resources).

In addition to helping you with your math skills, I will also teach you how to incorporate those skills into object-oriented programming using Java. If you are familiar with other object-oriented programming languages such as C#, you should have no difficulty porting this material from Java to those other programming languages.

Lots of graphics

Since most computer games make heavy use of either 2D or 3D graphics, you will need skills in the mathematical areas that are required for success in 2D and 3D graphics programming. As a minimum, this includes but is not limited to skills in:

  • Geometry
  • Trigonometry
  • Vectors
  • Matrices
  • 2D and 3D transforms
  • Transformations between coordinate systems
  • Projections

Of course, game programming requires mathematical skills beyond those required for graphics. However, for starters, this series will concentrate on the last five items in the above list.

The Kjell tutorials

In this series, I will frequently refer you to an excellent interactive tutorial on Vector Math for 3D Computer Graphics by Dr. Bradley P. Kjell (see Resources) for the required technical background. I will then teach you how to incorporate the knowledge that you gain from Kjell's tutorial into Java code with a heavy emphasis on object-oriented programming.

In the process, I will develop and explain a game-programming math library that you can use to experiment with and to confirm what you learn about vectors and matrices from the Kjell tutorial. The library will start out small and will grow as we progress through more and more material in subsequent lessons.

What you have learned

In the previous lesson, you learned how to update the game-math library to provide new capabilities including the addition of graphics and set methods for column matrices, points, vectors, and lines. You also learned how to draw on off-screen images.

What you will learn

In this lesson, you will learn how to compare column matrices for equality, compare two points for equality, compare two vectors for equality, add one column matrix to another, subtract one column matrix from another, and get a displacement vector from one point to another.

I also recommend that you concurrently study the Kjell tutorial down through Chapter 2 - Column and Row Matrix Addition (see Resources).

Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.

Figures

  • Figure 1. Screen output from the program named ColMatrixEquals01.
  • Figure 2. Screen output from the program named DisplacementVector01.
  • Figure 3. Screen output from the program named ColMatrixAddSubtract01.

Listings

  • Listing 1. Overridden equals method of the GM2D03.ColMatrix class.
  • Listing 2. Overridden equals method of the GM2D03.Point class.
  • Listing 3. The getColMatrix method of the GM2D03.Point class.
  • Listing 4. Beginning of the ColMatrixEquals01 class.
  • Listing 5. Remainder of the ColMatrixEquals01 class.
  • Listing 6. The getDisplacementVector method of the GM2D03.Point class.
  • Listing 7. The program named DisplacementVector01.
  • Listing 8. Source code for the program named ColMatrixAddSubtract01.
  • Listing 9. Source code for the add method of the GM2D03.ColMatrix class.
  • Listing 10. Source code for the subtract method of the GM2D03.ColMatrix class.
  • Listing 11. Source code for game-math library named GM2D03.
  • Listing 12. Source code for the program named ColMatrixEquals01.
  • Listing 13. Source code for the program named DisplacementVector01.
  • Listing 14. Source code for the program named ColMatrixAddSubtract01.

Supplementary material

I recommend that you also study the other lessons in my extensive collection of online Java tutorials. You will find a consolidated index at www.DickBaldwin.com.

Preview

As mentioned earlier, in this lesson you will learn how to:

  • Compare two column matrices for equality.
  • Compare two points for equality.
  • Compare two vectors for equality.
  • Add one column matrix to another.
  • Subtract one column matrix from another.
  • Get a displacement vector from one point to another.

To assist you in this quest, I will present and explain modifications that were made to update the game-math library that you learned about in the previous two lessons. In addition, I will present and explain three sample programs that illustrate the new features of the game-math library.

Discussion and sample code

 
Testing
All of the programs in this lesson were tested using JDK 1.6 running under Windows XP.

Much of the code in the library remains unchanged. I explained that code in the previous lesson (see Resources) and I won't repeat that explanation in this lesson. Rather, in this lesson, I will concentrate on explaining the modifications that I made to the library.

The game-math library named GM2D03

A complete listing of the library program is provided in Listing 11 near the end of the lesson.

This update added the following new capabilities:

  • Compare two ColMatrix objects for equality by implementing Kjell's rules for equality given in his Chapter 1, topic "Column Matrix Equality." The equality test does not test for absolute equality. Rather, It compares the values stored in two matrices and returns true if the values are equal or almost equal and returns false otherwise.
  • Get a reference to the ColMatrix object that defines a Point object.
  • Compare two Point objects for equality based on a comparison of the ColMatrix objects that define them.
  • Get a reference to the ColMatrix object that defines a Vector object.
  • Compare two Vector objects for equality based on a comparison of the ColMatrix objects that define them.
  • Add one ColMatrix object to a second ColMatrix object, returning a ColMatrix object.
  • Subtract one ColMatrix object from a second ColMatrix object, returning a ColMatrix object.
  • Get a displacement vector from one Point object to a second Point object. The vector points from the object on which the getDisplacementVector method is called to the object passed as a parameter to the method.

I will explain these updates in conjunction with the discussions of the programs that follow.

The sample program named ColMatrixEquals01

A complete listing of this program is provided in Listing 12 near the end of the lesson. I will explain the program in fragments. In selecting the portions of the program that I will explain, I will skip over material that is very similar to code that I have previously explained.

The purpose of this program is to confirm the behavior of the equals methods of the GM2D03.ColMatrix, Point, and Vector classes.

Overridden equals method of the GM2D03.ColMatrix class

I will begin by explaining some of the equals methods in the GM2D03 game-math library.

The first fragment shows the new equals method of the ColMatrix class.

Listing 1. Overridden equals method of the GM2D03.ColMatrix class.

    public boolean equals(Object obj){
      if(obj instanceof GM2D03.ColMatrix &&
         Math.abs(((GM2D03.ColMatrix)obj).getData(0) - 
                                 getData(0)) <= 0.00001 &&
         Math.abs(((GM2D03.ColMatrix)obj).getData(1) - 
                                  getData(1)) <= 0.00001){
        return true;
      }else{
        return false;
      }//end else
     
    }//end overridden equals method

This method overrides the equals method inherited from the Object class. It compares the double values stored in two matrices and returns true if the values are equal or almost equal and returns false otherwise.

 
An example of the problem
See Figure 3 where the a value that should be 0.0 is actually given by
-1.7763568394002505E-15

An inherent problem when comparing doubles and floats

There is always a problem when comparing two double or float values for equality. If you perform a series of computations twice, using a different computational order for each set of computations, you are likely to end up with two values that are not absolutely equal even if they should be. Arithmetic inaccuracies along the way may cause the two results to differ ever so slightly. However, they may be equal from a practical viewpoint.

Therefore, when comparing two double or float values for equality, it is customary to subtract one from the other, convert the difference to an absolute value, and compare that absolute value with an arbitrarily small positive value. If the difference is less than that the test value, the two original values are declared to be equal. Otherwise, they are declared to be unequal.

This is the logic that is implemented in Listing 1, which shouldn't require further explanation.

Overridden equals method of the GM2D03.Point class

Listing 2 presents the overridden equals method of the GM2D03.Point class.

Listing 2. Overridden equals method of the GM2D03.Point class.

    public boolean equals(Object obj){
      if(point.equals(((GM2D03.Point)obj).
                                         getColMatrix())){
        return true;
      }else{
        return false;
      }//end else
     
    }//end overridden equals method

This method also overrides the equals method inherited from the Object class. It compares the values stored in the ColMatrix objects that define two Point objects and returns true if they are equal and false otherwise.

One possible point of confusion

The one thing that can be confusing in Listing 2 has to do with the variable named point. This is a reference to an object of type ColMatrix that defines the location of the Point object. Listing 2 calls another new method named getColMatrix to get access to the ColMatrix object that defines the incoming Point object, and uses that object for the comparison. In effect, this method actually compares two objects of the ColMatrix class by calling the method that I explained in Listing 1. This illustrates the advantages of building up the library classes using objects of the fundamental ColMatrix class.

The getColMatrix method of the GM2D03.Point class

This extremely simple new method, which is called by the code in Listing 2, is presented in Listing 3.

Listing 3. The getColMatrix method of the GM2D03.Point class.

    //Returns a reference to the ColMatrix object that
    // defines this Point object.
    public GM2D03.ColMatrix getColMatrix(){
      return point;
    }//end getColMatrix

Listing 3 shouldn't require any explanation beyond the embedded comments.

Overridden equals method of the GM2D03.Vector class

The overridden equals method of the GM2D03.Vector class is essentially the same as the code shown for the Point class in Listing 2 so I won't bother to show and explain it. You van view this new method in Listing 11.

Beginning of the ColMatrixEquals01 program class

Listing 4 presents the beginning of the ColMatrixEquals01 program class including the beginning of the main method.

Listing 4. Beginning of the ColMatrixEquals01 class.

public class ColMatrixEquals01{
  public static void main(String[] args){
    GM2D03.ColMatrix matA = 
                           new GM2D03.ColMatrix(1.5,-2.6);
    GM2D03.ColMatrix matB = 
                           new GM2D03.ColMatrix(1.5,-2.6);
    GM2D03.ColMatrix matC = 
                 new GM2D03.ColMatrix(1.500001,-2.600001);
    GM2D03.ColMatrix matD = 
                   new GM2D03.ColMatrix(1.50001,-2.60001);
    System.out.println(matA.equals(matA));
    System.out.println(matA.equals(matB));
    System.out.println(matA.equals(matC));
    System.out.println(matA.equals(matD));

Listing 4 instantiates four different ColMatrix objects and then compares them in different ways, displaying the results of the comparisons on the command-line screen.

Screen output from the program named ColMatrixEquals01

The first four lines of text in Figure 1 were produced by the code in Listing 4. (The remaining output shown in Figure 1 was produced by the code in Listing 5, which I will explain shortly.)

Figure 1. Screen output from the program named ColMatrixEquals01.

true
true
true
false

true
true
false

true
true
false

Because of the simplicity of the code in Listing 4, you shouldn't need any help in understanding why the code in Listing 4 produced the first four lines of output in Figure 1.

The third and fourth lines of output in Figure 1 are the result of comparing two matrices whose values are almost equal but not absolutely equal.

Remainder of the ColMatrixEquals01 class

The remainder of the program named ColMatrixEquals01 is shown in Listing 5. The output produced by this code is shown in the last six lines of text in Figure 1.

Listing 5. Remainder of the ColMatrixEquals01 class.

    GM2D03.Point pointA = new GM2D03.Point(
                       new GM2D03.ColMatrix(15.6,-10.11));
    GM2D03.Point pointB = new GM2D03.Point(
                       new GM2D03.ColMatrix(15.6,-10.11));
    GM2D03.Point pointC = new GM2D03.Point(
                       new GM2D03.ColMatrix(-15.6,10.11));
    System.out.println(/*Blank line*/);
    System.out.println(pointA.equals(pointA));
    System.out.println(pointA.equals(pointB));
    System.out.println(pointA.equals(pointC));
    
    GM2D03.Vector vecA = new GM2D03.Vector(
                       new GM2D03.ColMatrix(15.6,-10.11));
    GM2D03.Vector vecB = new GM2D03.Vector(
                       new GM2D03.ColMatrix(15.6,-10.11));
    GM2D03.Vector vecC = new GM2D03.Vector(
                       new GM2D03.ColMatrix(-15.6,10.11));
    System.out.println(/*Blank line*/);
    System.out.println(vecA.equals(vecA));
    System.out.println(vecA.equals(vecB));
    System.out.println(vecA.equals(vecC));

  }//end main
}//end ColMatrixEquals01 class

Once again, the code in Listing 5 is very straightforward and shouldn't require further explanation. The screen output shown in Figure 1 verifies that the library methods called by this program behave appropriately.

The sample program named DisplacementVector01

A displacement vector describes the distance and direction that you would have to move to get from one point in space to another point in space.

The getDisplacementVector method of the GM2D03.Point class

Listing 6 presents the new getDisplacementVector method of the GM2D03.Point class

Listing 6. The getDisplacementVector method of the GM2D03.Point class.

    public GM2D03.Vector getDisplacementVector(
                                      GM2D03.Point point){
      return new GM2D03.Vector(new GM2D03.ColMatrix(
                            point.getData(0)-getData(0),
                            point.getData(1)-getData(1)));
    }//end getDisplacementVector

This method gets a displacement vector from one Point object to a second Point object and returns the result as a reference to a new object of the class GM2D03.Vector.

The direction of the vector

The displacement vector points from the Point object on which the method is called to the Point object passed as a parameter to the method. Kjell describes the component parts of the new vector as the distance you would have to walk, first along the x-axis and then along the y-axis to get from the first point to the second point. Of course, you could take the short cut and walk directly from the first point to the second point but that's often not how we do it in programming.

The code in Listing 6 is straightforward and shouldn't require further explanation.

The program named DisplacementVector01

Listing 7 shows the program named DisplacementVector01 in its entirety. (For convenience, a second copy of this program is provided in Listing 13 near the end of the lesson along with the other three programs discussed in this lesson.)

Listing 7. The program named DisplacementVector01.

public class DisplacementVector01{
  public static void main(String[] args){
    GM2D03.Point pointA = new GM2D03.Point(
                          new GM2D03.ColMatrix(6.5,-9.7));
    GM2D03.Point pointB = new GM2D03.Point(
                          new GM2D03.ColMatrix(-6.0,9.0));
    
    System.out.println(pointA.getDisplacementVector(
                                                 pointB));
    System.out.println(pointB.getDisplacementVector(
                                                 pointA));

  }//end main
}//end DisplacementVector01 class

The purpose of this program is to confirm the behavior of the getDisplacementVector method of the GM2D03.Point class, and the screen output shown in Figure 2 provides that confirmation.

Screen output from the program named DisplacementVector01

The screen output from the program named DisplacementVector01 is shown in Figure 2.

Figure 2. Screen output from the program named DisplacementVector01.

-12.5,18.7
12.5,-18.7

You should be able to correlate the results shown in Figure 2 with the code in Listing 6 and Listing 7 without further explanation.

Very simple methods

By now you may be thinking that the code in the game-math library is very simple and easy to understand. I hope that is the case. I went to great lengths to modularize the library into a set of simple and easily understood methods. Taken as a whole, however, the library is becoming quite powerful, and will become even more powerful as we progress through additional lessons.

The sample program named ColMatrixAddSubtract01

The source code for this program is shown in its entirety in Listing 8. (The source code is also provided in Listing 14 near the end of the lesson for convenience.)

Listing 8. Source code for the program named ColMatrixAddSubtract01.

public class ColMatrixAddSubtract01{
  public static void main(String[] args){

    GM2D03.ColMatrix matrixA = 
                         new GM2D03.ColMatrix(3.14,-6.01);
    GM2D03.ColMatrix matrixB = 
                        new GM2D03.ColMatrix(-14.0,-12.2);

    GM2D03.ColMatrix matrixC = matrixA.add(matrixB);
    GM2D03.ColMatrix matrixD = matrixC.subtract(matrixA);
    GM2D03.ColMatrix matrixE = matrixD.subtract(matrixB);

    System.out.println(matrixC);
    System.out.println(matrixD);
    System.out.println(matrixE);
  }//end main

}//end class ColMatrixAddSubtract01

The purpose of this program is to confirm the behavior of the new add and subtract methods of the GM2D03.ColMatrix class.

Source code for the add method of the GM2D03.ColMatrix class

The source code for this method is shown in Listing 9. The method adds one ColMatrix object to another ColMatrix object, returning a ColMatrix object. The order in which the two objects are added doesn't matter.

Listing 9. Source code for the add method of the GM2D03.ColMatrix class.

    public GM2D03.ColMatrix add(GM2D03.ColMatrix matrix){
      return new GM2D03.ColMatrix(
                            getData(0)+matrix.getData(0),
                            getData(1)+matrix.getData(1));
    }//end add

The code in the method is straightforward and shouldn't require an explanation.

Source code for the subtract method of the GM2D03.ColMatrix class

The source code for this method is shown in Listing 10. This method subtracts one ColMatrix object from another ColMatrix object, returning a ColMatrix object. In this case, the order of the operation does matter. The object that is received as an incoming parameter is subtracted from the object on which the method is called.

Listing 10. Source code for the subtract method of the GM2D03.ColMatrix class.

    public GM2D03.ColMatrix subtract(
                                 GM2D03.ColMatrix matrix){
      return new GM2D03.ColMatrix(
                            getData(0)-matrix.getData(0),
                            getData(1)-matrix.getData(1));
    }//end subtract

Once again, the code in the method is straightforward and shouldn't require an explanation.

Program output for program named ColMatrixAddSubtract01

Now, lets get back to the program named ColMatrixAddSubtract01 that is shown in Listing 8. This program produces the output shown in Figure 3.

Figure 3. Screen output from the program named ColMatrixAddSubtract01.

-10.86,-18.21
-14.0,-12.200000000000001
0.0,-1.7763568394002505E-15

By now, you should have no difficulty understanding how the output shown in Figure 3 was produced by the code shown in Listing 8. Note, however, that the last value on the third row should be 0.0 instead of the extremely small value shown. This is an example of an inherent problem having to do with comparing double or float values with other double or float values for absolute equality.

Run the programs

I encourage you to copy the code from Listing 12, Listing 13, and Listing 14, compile it, and execute it in conjunction with the game-math library provided in Listing 11.  Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.

Summary

In this lesson, you learned how to compare column matrices for equality, compare two points for equality, compare two vectors for equality, add one column matrix to another, subtract one column matrix from another, and get a displacement vector from one point to another.

What's next?

In the next lesson, you will learn:

  • How to add two or more vectors.
  • About the head-to-tail rule in vector addition.
  • About the vector addition parallelogram.
  • About the relationship between the length of the sum of vectors and the lengths of the individual vectors in the sum.
  • How to add a vector to a point.
  • How to get the length of a vector.
  • How to represent an object in different coordinate frames.

Resources

Complete program listings

Complete listings of the programs discussed in this lesson are shown in Listing 11 through Listing 14 below.

Listing 11. Source code for game-math library named GM2D03.

/*GM2D03.java
Copyright 2008, R.G.Baldwin
Revised 02/10/08

The name GM2Dnn is an abbreviation for GameMath2Dnn.

See the file named GM2D01.java for a general description
of this game-math library file. This file is an update of
GM2D02.

This update added the following new capabilities:

Compare two ColMatrix objects for equality by implementing
Kjell's rules for equality given in his Chapter 1, topic
"Column Matrix Equality." The equality test does not test
for absolute equality.  Rather, It compares the values
stored in two matrices and returns true if the values are
equal or almost equal and returns false otherwise.

Get a reference to the ColMatrix object that defines
a Point object.

Compare two Point objects for equality based on a
comparison of the ColMatrix objects that define them.

Get a reference to the ColMatrix object that defines
a Vector object.

Compare two Vector objects for equality based on a
comparison of the ColMatrix objects that define them.

Add one ColMatrix object to a second ColMatrix object,
returning a ColMatrix object.

Subtract one ColMatrix object from a second ColMatrix
object, returning a ColMatrix object.

Get a displacement vector from one Point object to a
second Point object. The vector points from the object
on which the getDisplacementVector method is called to the
object passed as a parameter to the method.

Tested using JDK 1.6 under WinXP.
*********************************************************/
import java.awt.geom.*;
import java.awt.*;

public class GM2D03{

  //An object of this class represents a 2D column matrix.
  // An object of this class is the fundamental building
  // block for several of the other classes in the
  // library.
  public static class ColMatrix{
    double[] data = new double[2];

    public ColMatrix(double data0,double data1){
      data[0] = data0;
      data[1] = data1;
    }//end constructor
    //--------------------------------------------------//

    public String toString(){
      return data[0] + "," + data[1];
    }//end overridden toString method
    //--------------------------------------------------//

    public double getData(int index){
      if((index < 0) || (index > 1)){ 
        throw new IndexOutOfBoundsException();
      }else{
        return data[index];
      }//end else
    }//end getData method
    //--------------------------------------------------//

    public void setData(int index,double data){
      if((index < 0) || (index > 1)){ 
        throw new IndexOutOfBoundsException();
      }else{
        this.data[index] = data;
      }//end else
    }//end setData method
    //--------------------------------------------------//

    //This method overrides the equals method inherited
    // from the class named Object. It compares the values
    // stored in two matrices and returns true if the
    // values are equal or almost equal and returns false
    // otherwise. 
    public boolean equals(Object obj){
      if(obj instanceof GM2D03.ColMatrix &&
         Math.abs(((GM2D03.ColMatrix)obj).getData(0) - 
                                 getData(0)) <= 0.00001 &&
         Math.abs(((GM2D03.ColMatrix)obj).getData(1) - 
                                  getData(1)) <= 0.00001){
        return true;
      }else{
        return false;
      }//end else

    }//end overridden equals method
    //--------------------------------------------------//

    //Adds one ColMatrix object to another ColMatrix
    // object, returning a ColMatrix object.
    public GM2D03.ColMatrix add(GM2D03.ColMatrix matrix){
      return new GM2D03.ColMatrix(
                            getData(0)+matrix.getData(0),
                            getData(1)+matrix.getData(1));
    }//end add
    //--------------------------------------------------//

    //Subtracts one ColMatrix object from another
    // ColMatrix object, returning a ColMatrix object. The
    // object that is received as an incoming parameter 
    // is subtracted from the object on which the method
    // is called.
    public GM2D03.ColMatrix subtract(
                                 GM2D03.ColMatrix matrix){
      return new GM2D03.ColMatrix(
                            getData(0)-matrix.getData(0),
                            getData(1)-matrix.getData(1));
    }//end subtract
    //--------------------------------------------------//
  }//end class ColMatrix
  //====================================================//

  public static class Point{
    GM2D03.ColMatrix point;

    public Point(GM2D03.ColMatrix point){//constructor
      //Create and save a clone of the ColMatrix object
      // used to define the point to prevent the point
      // from being corrupted by a later change in the
      // values stored in the original ColVector object
      // through use of its set method.
      this.point = 
         new ColMatrix(point.getData(0),point.getData(1));
    }//end constructor
    //--------------------------------------------------//

    public String toString(){
      return point.getData(0) + "," + point.getData(1);
    }//end toString
    //--------------------------------------------------//

    public double getData(int index){
      if((index < 0) || (index > 1)){ 
        throw new IndexOutOfBoundsException();
      }else{
        return point.getData(index);
      }//end else
    }//end getData
    //--------------------------------------------------//

    public void setData(int index,double data){
      if((index < 0) || (index > 1)){ 
        throw new IndexOutOfBoundsException();
      }else{
        point.setData(index,data);
      }//end else
    }//end setData
    //--------------------------------------------------//

    //This method draws a small circle around the location
    // of the point on the specified graphics context.
    public void draw(Graphics2D g2D){
      Ellipse2D.Double circle = 
                        new Ellipse2D.Double(getData(0)-3,
                                             getData(1)-3,
                                             6,
                                             6);
      g2D.draw(circle);
    }//end draw
    //--------------------------------------------------//

    //Returns a reference to the ColMatrix object that
    // defines this Point object.
    public GM2D03.ColMatrix getColMatrix(){
      return point;
    }//end getColMatrix
    //--------------------------------------------------//

    //This method overrides the equals method inherited
    // from the class named Object. It compares the values
    // stored in the ColMatrix objects that define two
    // Point objects and returns true if they are equal
    // and false otherwise. 
    public boolean equals(Object obj){
      if(point.equals(((GM2D03.Point)obj).
                                         getColMatrix())){
        return true;
      }else{
        return false;
      }//end else
     
    }//end overridden equals method
    //--------------------------------------------------//

    //Gets a displacement vector from one Point object to
    // a second Point object. The vector points from the
    // object on which the method is called to the object
    // passed as a parameter to the method. Kjell
    // describes this as the distance you would have to
    // walk along the x and then the y axes to get from
    // the first point to the second point.
    public GM2D03.Vector getDisplacementVector(
                                      GM2D03.Point point){
      return new GM2D03.Vector(new GM2D03.ColMatrix(
                            point.getData(0)-getData(0),
                            point.getData(1)-getData(1)));
    }//end getDisplacementVector
    //--------------------------------------------------//
  }//end class Point
  //====================================================//

  public static class Vector{
    GM2D03.ColMatrix vector;

    public Vector(GM2D03.ColMatrix vector){//constructor
      //Create and save a clone of the ColMatrix object
      // used to define the vector to prevent the vector
      // from being corrupted by a later change in the
      // values stored in the original ColVector object.
      this.vector = new ColMatrix(
                     vector.getData(0),vector.getData(1));
    }//end constructor
    //--------------------------------------------------//

    public String toString(){
      return vector.getData(0) + "," + vector.getData(1);
    }//end toString
    //--------------------------------------------------//

    public double getData(int index){
      if((index < 0) || (index > 1)){
        throw new IndexOutOfBoundsException();
      }else{
        return vector.getData(index);
      }//end else
    }//end getData
    //--------------------------------------------------//

    public void setData(int index,double data){
      if((index < 0) || (index > 1)){ 
        throw new IndexOutOfBoundsException();
      }else{
        vector.setData(index,data);
      }//end else
    }//end setData
    //--------------------------------------------------//

    //This method draws a vector on the specified graphics
    // context, with the tail of the vector located at a
    // specified point, and with a small circle at the
    // head.
    public void draw(Graphics2D g2D,GM2D03.Point tail){
      Line2D.Double line = new Line2D.Double(
                       tail.getData(0),
                       tail.getData(1),
                       tail.getData(0)+vector.getData(0),
                       tail.getData(1)+vector.getData(1));

    //Draw a small circle to identify the head.
      Ellipse2D.Double circle = new Ellipse2D.Double(
                      tail.getData(0)+vector.getData(0)-2,
                      tail.getData(1)+vector.getData(1)-2,
                      4,
                      4);
      g2D.draw(circle);
      g2D.draw(line);
    }//end draw
    //--------------------------------------------------//

    //Returns a reference to the ColMatrix object that
    // defines this Vector object.
    public GM2D03.ColMatrix getColMatrix(){
      return vector;
    }//end getColMatrix
    //--------------------------------------------------//

    //This method overrides the equals method inherited
    // from the class named Object. It compares the values
    // stored in the ColMatrix objects that define two
    // Vector objects and returns true if they are equal
    // and false otherwise. 
    public boolean equals(Object obj){
      if(vector.equals((
                     (GM2D03.Vector)obj).getColMatrix())){
        return true;
      }else{
        return false;
      }//end else

    }//end overridden equals method
    //--------------------------------------------------//
  }//end class Vector
  //====================================================//

  //A line is defined by two points. One is called the
  // tail and the other is called the head.
  public static class Line{
    GM2D03.Point[] line = new GM2D03.Point[2];

    public Line(GM2D03.Point tail,GM2D03.Point head){
      //Create and save clones of the points used to
      // define the line to prevent the line from being 
      // corrupted by a later change in the coordinate
      // values of the points.
      this.line[0] = new Point(new GM2D03.ColMatrix(
                        tail.getData(0),tail.getData(1)));
      this.line[1] = new Point(new GM2D03.ColMatrix(
                        head.getData(0),head.getData(1)));
    }//end constructor
    //--------------------------------------------------//

    public String toString(){
      return "Tail = " + line[0].getData(0) + "," 
             + line[0].getData(1) + "\nHead = " 
             + line[1].getData(0) + "," 
             + line[1].getData(1);
    }//end toString
    //--------------------------------------------------//

    public GM2D03.Point getTail(){
      return line[0];
    }//end getTail
    //--------------------------------------------------//

    public GM2D03.Point getHead(){
      return line[1];
    }//end getHead
    //--------------------------------------------------//

    public void setTail(GM2D03.Point newPoint){
      //Create and save a clone of the new point to
      // prevent the line from being corrupted by a
      // later change in the coordinate values of the
      // point.
      this.line[0] = new Point(new GM2D03.ColMatrix(
              newPoint.getData(0),newPoint.getData(1)));
    }//end setTail
    //--------------------------------------------------//

    public void setHead(GM2D03.Point newPoint){
      //Create and save a clone of the new point to
      // prevent the line from being corrupted by a
      // later change in the coordinate values of the
      // point.
      this.line[1] = new Point(new GM2D03.ColMatrix(
              newPoint.getData(0),newPoint.getData(1)));
    }//end setHead
    //--------------------------------------------------//

    public void draw(Graphics2D g2D){
      Line2D.Double line = new Line2D.Double(
                                    getTail().getData(0),
                                    getTail().getData(1),
                                    getHead().getData(0),
                                    getHead().getData(1));
      g2D.draw(line);
    }//end draw
    //--------------------------------------------------//
  }//end class Line
  //====================================================//

}//end class GM2D03

 

Listing 12. Source code for the program named ColMatrixEquals01.

/*ColMatrixEquals01.java
Copyright 2008, R.G.Baldwin
Revised 02/08/08

The purpose of this program is to confirm the behavior of
the equals methods of the GM2D03.ColMatrix, Point, and
Vector classes.

Tested using JDK 1.6 under WinXP.
*********************************************************/

public class ColMatrixEquals01{
  public static void main(String[] args){
    GM2D03.ColMatrix matA = 
                           new GM2D03.ColMatrix(1.5,-2.6);
    GM2D03.ColMatrix matB = 
                           new GM2D03.ColMatrix(1.5,-2.6);
    GM2D03.ColMatrix matC = 
                 new GM2D03.ColMatrix(1.500001,-2.600001);
    GM2D03.ColMatrix matD = 
                   new GM2D03.ColMatrix(1.50001,-2.60001);
    System.out.println(matA.equals(matA));
    System.out.println(matA.equals(matB));
    System.out.println(matA.equals(matC));
    System.out.println(matA.equals(matD));

    GM2D03.Point pointA = new GM2D03.Point(
                       new GM2D03.ColMatrix(15.6,-10.11));
    GM2D03.Point pointB = new GM2D03.Point(
                       new GM2D03.ColMatrix(15.6,-10.11));
    GM2D03.Point pointC = new GM2D03.Point(
                       new GM2D03.ColMatrix(-15.6,10.11));
    System.out.println(/*Blank line*/);
    System.out.println(pointA.equals(pointA));
    System.out.println(pointA.equals(pointB));
    System.out.println(pointA.equals(pointC));

    GM2D03.Vector vecA = new GM2D03.Vector(
                       new GM2D03.ColMatrix(15.6,-10.11));
    GM2D03.Vector vecB = new GM2D03.Vector(
                       new GM2D03.ColMatrix(15.6,-10.11));
    GM2D03.Vector vecC = new GM2D03.Vector(
                       new GM2D03.ColMatrix(-15.6,10.11));
    System.out.println(/*Blank line*/);
    System.out.println(vecA.equals(vecA));
    System.out.println(vecA.equals(vecB));
    System.out.println(vecA.equals(vecC));

  }//end main
}//end ColMatrixEquals01 class

 

Listing 13. Source code for the program named DisplacementVector01.

tr>
/*DisplacementVector01.java
Copyright 2008, R.G.Baldwin
Revised 02/08/08

The purpose of this program is to confirm the behavior of
the getDisplacementVector method of the GM2D03.Point
class.

Tested using JDK 1.6 under WinXP.
*********************************************************/

public class DisplacementVector01{
  public static void main(String[] args){
    GM2D03.Point pointA = new GM2D03.Point(
                          new GM2D03.ColMatrix(6.5,-9.7));
    GM2D03.Point pointB = new GM2D03.Point(
                          new GM2D03.ColMatrix(-6.0,9.0));

    System.out.println(pointA.getDisplacementVector(
                                                 pointB));
    System.out.println(pointB.getDisplacementVector(
                                                 pointA));

  }//end main
}//end DisplacementVector01 class

 

Listing 14. Source code for the program named ColMatrixAddSubtract01.

/*ColMatrixAddSubtract01.java
Copyright 2008, R.G.Baldwin
Revised 02/08/08

The purpose of this program is to confirm the behavior of
the add and subtract methods of the GM2D03.ColMatrix
class.

Tested using JDK 1.6 under WinXP.
*********************************************************/

public class ColMatrixAddSubtract01{
  public static void main(String[] args){

    GM2D03.ColMatrix matrixA = 
                         new GM2D03.ColMatrix(3.14,-6.01);
    GM2D03.ColMatrix matrixB = 
                        new GM2D03.ColMatrix(-14.0,-12.2);

    GM2D03.ColMatrix matrixC = matrixA.add(matrixB);
    GM2D03.ColMatrix matrixD = matrixC.subtract(matrixA);
    GM2D03.ColMatrix matrixE = matrixD.subtract(matrixB);

    System.out.println(matrixC);
    System.out.println(matrixD);
    System.out.println(matrixE);
  }//end main

}//end class ColMatrixAddSubtract01

 


Copyright

Copyright 2008, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP). His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments. (TI is still a world leader in DSP.) In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel