Saturday 17 October 2009

Vectors, Matrices and C++



This week in the Introduction to 3D Graphics Programming module we have been programming our own matrix class. So some revision on the good old matrices we met back in the Computational Mathematics module (from last year) was key. The same can be said for the vector class we had programmed from last week.

So before we could all start any programming we had to be perfectly clear on, not only what a vector and matrix was but also several important operations that are carried out whilst using vectors and matrices. To enforce this we was asked to revise as we’d all be taking a test on them. The list contains everything I had studied and revised before taking the in-class tests.

  • Vector Addition & Subtraction
  • (Vector) Scalar Multiplication
  • Obtaining a Vectors Magnitude
  • Normalizing a Vector (obtaining the unit vector)
  • The Dot Product
  • The Cross Product
  • Matrix Addition & Subtraction
  • (Matrix) Scalar Multiplication
  • Matrix - Matrix Multiplication
  • Vector - Matrix Multiplication
  • The Transpose of a Matrix
  • The Identity Matrix

Once we had finished our tests we got given a Visual Studio solution with header files and source files for the vector and matrix classes (vectors was last week). These files contained minimal amounts of code as they were just interfaces to work with, we were all expected to program the functionality for the majority of the above vector/matrix operations. This was surprisingly fun for me to program, I didn’t really expect to find it so entertaining (I don’t get out much). Anyway I have provided screenshots of some of my code for performing some of the above operations, see below. If you have any trouble seeing the code it's probably because the images have been resized, just click on the image to get a bigger view.

So here's the code for finding the dot product in my vector class..


Here is the function used for testing that..


Here is the output..

Now the code for finding the cross product in my vector class..

The above code (looking at it a second time) is obviously inefficient and can be done better. The code in the screenshot below is a lot more efficient and a lot less expensive (computationally).

Here is the function used for testing that..


Now a little matrix code. Here is the code for my matrix addition..


It's probably worth mentioning here, that the matrix subtraction code is exactly the same as the addition. Where the addition sign is used the subtraction sign replaces it. Here is the output..

Now the code for matrix - matrix multiplication..


That's the clean way of doing it, before I coded the for loop it looked like this..


I'm not sure if the for loop is more efficient than the 'hard coded' version but its certainly easier to type in. Anyway here is the function used for testing that..

Here is the output..


No comments:

Post a Comment