GIDForums  

Go Back   GIDForums > Computer Programming Forums > CPP / C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 01-Apr-2008, 14:48
mosquito mosquito is offline
Junior Member
 
Join Date: Feb 2008
Posts: 40
mosquito is on a distinguished road

Need help - complex matrix, complex vector


Hi,

I have to generate a normalized d=2 dimensional complex vector. Moreover I also have to generate a unitary matrix, which has the form:

exp(i*sigma*epsilon), i is the imaginary unit, e.g. i =sqrt(-1),

where sigma is a Pauli matrix of 2x2, e.g. sigma = i*(something scalar elements).

I need some code in c++ defining these objects!
  #2  
Old 02-Apr-2008, 09:41
Blake's Avatar
Blake Blake is offline
Member
 
Join Date: Nov 2005
Posts: 172
Blake will become famous soon enough

Re: Need help - complex matrix, complex vector


What's this for? I have a matrix class a wrote awhile back that I would possibly let you use as long as it's not for a school assignment or proprietary software. It's designed for use with any variable type that has the *, +, and - operators defined.
__________________
www.blake-foster.com
  #3  
Old 02-Apr-2008, 10:01
mosquito mosquito is offline
Junior Member
 
Join Date: Feb 2008
Posts: 40
mosquito is on a distinguished road

Re: Need help - complex matrix, complex vector


No, it is not a school assignment and not a software or something like this... I need it only at home, I would fabricate my own code.
I should be glad to get it Thanks
  #4  
Old 02-Apr-2008, 10:10
Blake's Avatar
Blake Blake is offline
Member
 
Join Date: Nov 2005
Posts: 172
Blake will become famous soon enough

Re: Need help - complex matrix, complex vector


Here it is. If you use the determinant function, you'll probably want to modify it to row-reduce and then multiply the diagonals. It uses the method of minors right now, because I was using matrices of polynomials, and so I couldn't do the division that is necessary to use the row-reduction method.

You can use this for vectors too. Just create a matrix with only one column. If you implement vectors that way, you can do matrix-vector multiplication.

If you distribute the code at all I would appreciate credit in the source. A link to my website (www.blake-foster.com) would be nice.

EDIT: One more important note--all the indexes start from 1 instead of the usual 0. I did it that way to make it consistent with the notation used in math literature.

matrix.h:

CPP / C++ / C Code:
#ifndef MATRIX_H
#define MATRIX_H
#include <vector>
#include <iostream>
#include <math>

using namespace std;

// The class Matrix implements matrices with entries in an arbitrary field.
// Rows, columns, or individual elements may be accessed in constant time. Rows
// and columns may be inserted only onto the end, and columns may be deleted
// from the end. Elements may be indexed in row major order as well.

// ***All indexes for matrices start with 1.***

template <typename T>
class Matrix
{
  public:
    Matrix<T>(int,int, T); // create int x int matrix filled T
    Matrix<T>(int,int); // create int x int matrix filled with 0's
    Matrix<T>(); // create an empty matrix
    int numRows() const; // return the number of rows
    int numCols() const; // return the number of columns
    inline T* elem(int, int); // return a pointer to element (int,int).
    Matrix<T> getRow(int); // return row int as a matrix
    Matrix<T> getCol(int); // return column int as a matrix
    void setRow(int, Matrix<T>); // takes a matrix with numCols elements and stores
      //it in the (int)th column of THIS matrix.
    void setCol(int, Matrix<T>); // takes a matrix with numRows elements and
      //stores it in the (int)th row of THIS matrix.
    Matrix<T> operator*(const Matrix<T>&); // matrix multiplication.
    Matrix<T> operator*(const T&) const; // scalar multiplication.
    Matrix<T> operator/(const T&) const; // inverse scalar multiplication.
    // *** requires / operator to be implemented on T ***
    bool operator==(const Matrix<T>&); // element by element equality
    T* operator[](const int&); // returns the element of index int
      // (upper left to lower right, row major order)
    int length(); // the total number of elements
    Matrix<T> transpose(); // the transpose of THIS matrix (swap rows and columns)
    T determinant(); // the determinant
    void push_row_back(T); // push a row filled with zeros
    void push_col_back(T); // push a column filled with zeros
    void pop_col_back(); // delete the last collumn
    void pop_row_back(); // delete the last row
    T cofactor(const int&, const int&); // compute the (i,j)th cofactor
    Matrix<T> cofactor_matrix(); // compute cofactor matrix
    Matrix<T> adjoint_matrix(); // compute adjoint matrix
    Matrix<T> inverse(); // inverse matrix
    // *** requires / operator to be implemented on T ***
    void print();
  protected:
    int rows; // the number of rows
    int cols; // the number of columns
    vector<vector<T> > data; // the contents of the Matrix
};

template <typename T>
Matrix<T>::Matrix(int r, int c, T t) // construct an r x c matrix containing all zero's
 : rows(r), cols(c), data(vector<vector<T> >(0))
{
  for (int i=0; i < rows; ++i) data.push_back(vector<T>(cols,t));
}

template <typename T>
Matrix<T>::Matrix(int r, int c) // construct an r x c matrix containing all zero's
 : rows(r), cols(c), data(vector<vector<T> >(0))
{
  // initialize each row with a vector containing all zero's
  for (int i=0; i < rows; ++i) data.push_back(vector<T>(cols,T()));
}

template <typename T>
Matrix<T>::Matrix() // construct an empty Matrix
{
  Matrix<T>(0,0);
}

template <typename T>
int Matrix<T>::numRows() const {return rows;} // return the number of rows

template <typename T>
int Matrix<T>::numCols() const {return cols;} // return the number of columns

template <typename T>
inline T* Matrix<T>::elem(int r, int c) // return a pointer to the element in row r and
// column c (indexes start from 1)
{
  return &data[r-1][c-1];
}

template <typename T>
Matrix<T> Matrix<T>::getRow(int index) // return row (index) as a matrix
{
  Matrix<T> temp=Matrix<T>(1,cols); // creat a 1 x cols matrix
  temp.data[0]=data[index-1]; // copy row (index) of THIS matrix into temp
  return temp;
}

template <typename T>
Matrix<T> Matrix<T>::getCol(int index)  // return column (index) as a matrix
{
  Matrix<T> temp=Matrix<T>(rows,1); // creat a cols x 1 matrix
  for (int i=1; i<=rows; ++i)
  {
    // copy elements of column (index) into temp one at a time
    *temp.elem(i,1)=*elem(i,index);
  }
  return temp;
}

template <typename T>
void Matrix<T>::setRow(int index, Matrix<T> m) // replace row (index) of THIS Matrix
{
  if (m.length()!=cols)
  {
    cout<<endl<<"dimension mismatch"<<endl; // m must have the same number of
    // columns as THIS
    system("pause");
    return;
  }
  data[index-1]=m.data[0]; // copy m into row (index) of THIS Matrix
}

template <typename T>
void Matrix<T>::setCol(int index, Matrix<T> m)
{
  if (m.length()!=rows)
  {
    cout<<endl<<"dimension mismatch"<<endl; // m must have the same number of
    // rows as THIS
    system("pause");
    return;
  }
  for (int i=1; i<=rows; ++i) // iterate over all rows
  {
    *elem(i,index)=*m[i]; // copy the ith element of m into the ith position in
    // row (index) of THIS
  }
}

template <typename T>
Matrix<T> Matrix<T>::operator*(const Matrix<T>& m) // Matrix multiplication
{
  Matrix b=m; // make a copy of m
  if (cols != b.rows) // To multiply two matrices the number of colums of the
  // first must match the number of columns of the second
  {
    cout << "dimension mismatch" << endl;
    system("pause");
    return *this;
  }
  T acc=T()-T();
  // iterate over all possibilites for i and j, and use the formula for Matrix
  // multiplication to calculate element (i,j) of the product
  Matrix<T> c = Matrix<T>(rows,b.cols);
  for (int i=1; i<= c.rows; ++i)
  {
    for (int j=1; j<=c.cols; ++j)
    {
      acc=T()-T();
      for (int k=1; k<=cols; ++k)
      {
      // formula from:
        // Eric W. Weisstein. "Matrix Multiplication." From MathWorld--A Wolfram
        // Web Resource. [url]http://mathworld.wolfram.com/MatrixMultiplication.html[/url]
        acc=acc+(*elem(i,k)*(*b.elem(k,j)));
      }
      *c.elem(i,j)=acc;
    }
  }
  return c;
}

template <typename T>
Matrix<T> Matrix<T>::operator*(const T& t) const // scalar multiplication
{
  Matrix<T> M(*this);
  for (int r=1; r<=rows; ++r)
  {
    for (int c=1; c<=cols; ++c)
    {
      *M.elem(r,c) = (*M.elem(r,c))*t;
    }
  }
  return M;
}

template <typename T>
Matrix<T> Matrix<T>::operator/(const T& t) const // scalar multiplication
{
  Matrix<T> M(*this);
  for (int r=1; r<=rows; ++r)
  {
    for (int c=1; c<=cols; ++c)
    {
      *M.elem(r,c) = (*M.elem(r,c))/t;
    }
  }
  return M;
}


template <typename T>
bool Matrix<T>::operator==(const Matrix<T>& m) // test equality
{
  if (rows!=m.numRows() || cols!=m.numCols()) {return false;} // if the
  // dimensions don't match, there is no need to continue
  else for (int i=1; i<=rows; ++i) // if we have gotten this far, the dimensions
  // match, so now we have to check each element of both matrices
  {
    for (int j=1; j<=cols; ++j)
    {
      if (data[i][j]!=m.data[i][j]) {return false;} // If we find a position
      // where THIS and m are not equal, then return false
    }
  }
  return true; // if we have gotten this far, we have iterated through all
  // elements of THIS and m without finding any inequality, so they are equal
}

template <typename T>
T* Matrix<T>::operator[](const int& index) // return a pointer to an element
// indexed in row major order
{
  // change the index to (row, column) coordinates, and then call the elem
  // function
  int r=ceil((float)index/cols);
  int c=index%cols;
  if (c==0)
  {
    c=c+cols; // % does not work exactly like the actual modulus operator from
    // number theory on negative numbers.
  }
  return elem(r,c);
}

template <typename T>
int Matrix<T>::length() {return rows*cols;} // The total number of elements

template <typename T>
Matrix<T> Matrix<T>::transpose() // return the transpose of THIS Matrix (swap rows and
// columns)
{
  Matrix<T> m(cols,rows); // we will tempoarily store the output in m
  for (int i=1; i<=rows; ++i)
  {
    m.setCol(i,getRow(i)); // set the ith column of m equal to the ith row
  // of THIS Matrix
  }
  return m;
}

template <typename T>
T Matrix<T>::determinant()
{
  assert(rows==cols&&rows>=2);
  if (rows==2) return ((*elem(1,1))*(*elem(2,2)))-((*elem(1,2))*(*elem(2,1)));
  T acc(*elem(1,1)-*elem(1,1));
  for (int i=1; i<=cols; ++i)
  {
    Matrix<T> temp(rows-1,cols-1);
    int tempR=1;
    int tempC=1;
    for (int r=2; r<=rows; ++r)
    {
      for (int c=1; c<=cols; ++c)
      {
        if (c!=i)
        {
          *temp.elem(tempR,tempC)=*elem(r,c);
          ++tempC;
        }
      }
      tempC=1;
      ++tempR;
    }
    if (i%2==0) acc=acc-((*elem(1,i))*temp.determinant());
    else acc=acc+((*elem(1,i))*temp.determinant());
  }
  return acc;
}

template <typename T>
void Matrix<T>::push_row_back(T t) // add a new row
{
  data.push_back(vector<T>(cols,t)); // create a vector of all zero's and
  // add it to the bottom of THIS Matrix
  ++rows; // increment the number if rows
}

template <typename T>
void Matrix<T>::push_col_back(T t)
{
  for (int i=0; i<rows; ++i) // iterate over all rows
  {
    data[i].push_back(t); // add another element to the end of each row
  }
  ++cols; // increment the number of columns
}

template <typename T>
void Matrix<T>::pop_row_back() // add a new row
{
  data.pop_back(); // delete last row a row
  rows--; // decrement the number if rows
}

template <typename T>
void Matrix<T>::pop_col_back() // delete the last column
{
  for (int i=0; i<rows; ++i) // iterate over all rows
  {
    data[i].pop_back(); // delete the last element of each row
  }
  cols--; // decrement the number of columns
}

template <typename T>
T Matrix<T>::cofactor(const int& r, const int& c)
{
  Matrix<T> M(rows-1,cols-1);
  int src_row = 1;
  int src_column=1;
  for (int dest_row = 1; dest_row<rows; ++dest_row)
  {
    if (src_row==r) ++src_row; // scip row r
    for (int dest_column = 1; dest_column < cols; ++dest_column)
    {
      if (src_column==c) ++src_column; // skip column c
      *M.elem(dest_row,dest_column) = *elem(src_row,src_column);
      ++src_column;
    }
    ++src_row;
    src_column=1;
  }
  // determine sign
  if ((r+c)%2 == 0)  return M.determinant();
  else return -M.determinant();
}

template <typename T>
Matrix<T> Matrix<T>::cofactor_matrix()
{
  Matrix<T> M(rows,cols);
  // iterate over all elements and compute each cofactor
  for (int r = 1; r<=rows; ++r)
  {
    for (int c = 1; c<=cols; ++c)
    {
      *M.elem(r,c) = cofactor(r,c);
    }
  }
  return M;
}

template <typename T>
inline Matrix<T> Matrix<T>::adjoint_matrix()
{
  return cofactor_matrix().transpose();
}

template <typename T>
inline Matrix<T> Matrix<T>::inverse()
{
  return adjoint_matrix()/determinant();
}

template <typename T>
void Matrix<T>::print() // used to print a matrix
{
  cout<<endl; // start a new line
  // nested for loops iterate over the entire Matrix
  for (int i=1; i<=numRows(); ++i)
  {
    for (int j=1; j<=numCols(); ++j)
    {
      cout << *elem(i,j) << " "; // add element (i,j) to the ostream
    }
    cout<<endl; // add a new lone
  }
}

#endif

__________________
www.blake-foster.com
  #5  
Old 02-Apr-2008, 10:18
mosquito mosquito is offline
Junior Member
 
Join Date: Feb 2008
Posts: 40
mosquito is on a distinguished road

Re: Need help - complex matrix, complex vector


That's cool..

And if I want to have a complex vector or matrix, what type of definition do I need?
  #6  
Old 02-Apr-2008, 10:21
Blake's Avatar
Blake Blake is offline
Member
 
Join Date: Nov 2005
Posts: 172
Blake will become famous soon enough

Re: Need help - complex matrix, complex vector


You should make a complex number class. Incidentally, I have one which I wrote for a project in computer graphics. It supports all the usual arithmetical operators, and it can also be used with the cout.

complex.h

CPP / C++ / C Code:
#include <iostream.h>

/*
This is an implementation of the field of Complex numbers. Addition, subtraction,
multiplication, and division are defined, as well as the ==, !=, and << operators.
The data member a is a float which stores the real part and b is a float that stores
the imaginary part.
*/

class Complex
{
  friend ostream& operator<<(ostream&,const Complex&);
  public:
    Complex(float x, float y) : a(x), b(y) {}; // Constructor. First arg is the
      // real part and the second is the imaginary part.
    Complex(float x) : a(x), b(0) {}; // make a float into a Complex
    Complex() : a(0), b(0) {};
      // Default constructor. Creates Complex equal to zero.
    Complex operator+(const Complex& C)
      {return Complex(a+C.a, b+C.b);}
    Complex operator-(const Complex& C) //Subtraction
      {return Complex(a-C.a,b-C.b);}
    Complex operator-() //negation operator
      {return Complex(-a,-b);}
    Complex operator*(const Complex& C) // multiplication; (a1+b1i)*(a2+b2i) = a1a2-b1b2+(a1b2+a2b1)i
      {return Complex((a*C.a)-(b*C.b),(a*C.b)+(b*C.a));}
    Complex operator/(const Complex& C) // division; (a1+b1i)/(a2+b2i) = (a1a2+b1b2)/(a2^2+b2^2)+i(a2b1-a1b2)/(a2^2+b2^2)
      {
        float temp = 1/((C.a*C.a)+(C.b*C.b));
        return Complex(temp*((a*C.a)+(b*C.b)), temp*((b*C.a)-(a*C.b)));
      }
    bool operator==(const Complex& C) //both real and imaginary parts must be equal
      {return a==C.a&&b==C.b;}
    bool operator!=(const Complex& C)
      {return a!=C.a||b!=C.b;}
    float a; // the real part
    float b; // the imaginary part
};

ostream& operator<<(ostream& ost,const Complex& C) // concationate a Complex onto
// an ostream. Format is a+bi, with special cases.
{
  float a=C.a;
  float b=C.b;
  if (a!=0) ost<<a;
  if (b!=0)
  {
    if (b>0) ost<<'+';
    else if (b==-1) ost<<'-';
    if (b!=1) ost<<b;
    ost<<'i';
  }
  else if (a==0) ost<<0;
  return ost;
}

Now, you would say something like

CPP / C++ / C Code:
Matrix<Complex> M(2, 4);

This makes a 2 x 4 matrix of complex numbers.
__________________
www.blake-foster.com
  #7  
Old 02-Apr-2008, 10:51
mosquito mosquito is offline
Junior Member
 
Join Date: Feb 2008
Posts: 40
mosquito is on a distinguished road

Re: Need help - complex matrix, complex vector


And if I have a vector defined as follows:
CPP / C++ / C Code:
struct vector{float x, y, z;};

then is there any simple definition like this?

I have to use this a matrix calss what I have written before..
  #8  
Old 02-Apr-2008, 11:15
Blake's Avatar
Blake Blake is offline
Member
 
Join Date: Nov 2005
Posts: 172
Blake will become famous soon enough

Re: Need help - complex matrix, complex vector


You should use a Matrix with just one column for vectors, like this:

CPP / C++ / C Code:
Matrix<Complex> vec(3,1);

That makes a 3-dimensional complex vector.

If you really want to define vectors with a struct like you did above, it could be a bit hairy making it work with that Matrix class.
__________________
www.blake-foster.com
  #9  
Old 02-Apr-2008, 11:46
mosquito mosquito is offline
Junior Member
 
Join Date: Feb 2008
Posts: 40
mosquito is on a distinguished road

Re: Need help - complex matrix, complex vector


Indeed i should have a complex 2 dimensional unit vector instead of real vector defined abowe... And I also have a complex matrix instead of the rotational matrices...

More simple if I post here my code:

CPP / C++ / C Code:

struct vector{float x, y, z;};

/* ------_BEGIN_---------_MATRIX3x3_CLASS_-----------------*/
class Matrix3x3 {

private:
	float tomb[3][3];  // 3x3 matrix

public:
        void init(vector &a){ 

	tomb[0][0] = a.x * a.x;
	tomb[0][1] = a.x * a.y;
	tomb[0][2] = a.x * a.z;
	tomb[1][0] = a.y * a.x;
	tomb[1][1] = a.y * a.y;
	tomb[1][2] = a.y * a.z;
	tomb[2][0] = a.z * a.x;
	tomb[2][1] = a.z * a.y;
	tomb[2][2] = a.z * a.z;
    	}

 Matrix3x3 &operator +=(Matrix3x3 b){ //add to matrices
 int k,l;
 for(k=0; k<3; k++)
 for(l=0; l<3; l++) 
  tomb[k][l] += b.tomb[k][l];
 return *this;
 }

 Matrix3x3 &operator/=(float c){ //divide by a scalar
 int k,l;
 for(k=0; k<3; k++)
 for(l=0; l<3; l++)
  tomb[k][l] /= c;
 return *this;
 }

/**********_for_printout_**********/
void PrintMatrix()
{
 int i,j;
 
 for(i=0;i<3;i++)
   for(j=0;j<3;j++)
     printf("%f%s",tomb[i][j],(j==2)?"\n":" ");
}
};
/* --------_END_-----------_MATRIX3x3_CLASS_----------------*/


// Function prototypes
vector Rotate(float m[][3], vector v);

// main function
int main(void) {



	Matrix3x3 m[N];

	vector vec0 = {1.0/sqrtf(3.0),1.0/sqrtf(3.0),1.0/sqrtf(3.0)};

	int i;
	float phi, costheta, r, x, y, z;

	srand((unsigned)time(NULL));

		vec.x = 0;
		vec.y = 0;
		vec.z = 1;

	for (i = 0; i < N; i++) 
	{      
	    //  >>>>>>>>> ROTATION MATRICES <<<<<<<<<<<
    	float mX[3][3] = {
                             {1.0f, 0.0f, 0.0f},
                             {0.0f, cosf(epsilon), -sinf(epsilon)},
                             {0.0f, sinf(epsilon), cosf(epsilon)}
                             };
    	float mY[3][3] = {
                             {cosf(epsilon), 0.0f, sinf(epsilon)},
                             {0.0f, 1.0f, 0.0f},
                             {-sinf(epsilon), 0.0f, cosf(epsilon)}
                             };
    	float mZ[3][3] = {
                             {cosf(epsilon), -sinf(epsilon), 0.0f},
                             {sinf(epsilon), cosf(epsilon), 0.0f},
                             {0.0f, 0.0f, 1.0f}
                             };
	    //  >>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<

            switch (rand()%3) // a number that is either 0, 1, or 2
	    { 

        	case 0:
		//To rotate vec[i] about the X axis, call it with
    		vec = Rotate(mX, vec);
            	break;

        	case 1:
		//To rotate vec[i] about the Y axis, call it with
    		vec = Rotate(mY, vec);
            	break;

        	case 2:
		//To rotate vec[i] about the Z axis, call it with
    		vec = Rotate(mZ, vec);
            	break;
            }

		//code here to make a matrix from vec[i]
	        m[i].init(vec);
    	 }  // this is the end of the big loop through the N vectors


/****************************************************/

    	// will hold the sum of all of the matrices
    	// code to initialize the sum matrix to all zeros
    	Matrix3x3 sum = m[0]; 

    	for (i=0;i<N;i++) {
        // use the '+= operator to add each m[i] to sum
	sum += m[i];
    	}
        // use the /= operator to divide the sum matrix by scalar N
	sum /= N;
	

        // Now print the elements of sum
	sum.PrintMatrix();

return 0;
}

// Define a function that operates one of your vector structs
// with a matrix
//
// You send a matrix and a struct and return a struct
vector Rotate(float m[][3], vector v)
{
    vector returnv;
    returnv.x = m[0][0]*v.x + m[0][1]*v.y + m[0][2]*v.z;
    returnv.y = m[1][0]*v.x + m[1][1]*v.y + m[1][2]*v.z;
    returnv.z = m[2][0]*v.x + m[2][1]*v.y + m[2][2]*v.z;

    return returnv;
}
  #10  
Old 02-Apr-2008, 12:43
Blake's Avatar
Blake Blake is offline
Member
 
Join Date: Nov 2005
Posts: 172
Blake will become famous soon enough

Re: Need help - complex matrix, complex vector


Now I'm not sure what your question is. Are you trying to make that code work with complex numbers? If that's the case, you could use that complex number class I posted instead of floats.
__________________
www.blake-foster.com
 
 

Recent GIDBlog2nd Week of IA Training by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Calculating time ashraf_leaf CPP / C++ Forum 2 25-Feb-2008 18:03
Changing values at specific elements in a vector Brett5984 CPP / C++ Forum 3 18-Dec-2007 11:07
Gauss-Jordan Elimination on Matrices - Help Needed Max_Power82 CPP / C++ Forum 3 03-Dec-2006 21:41
Combining Vectors and References Frankg CPP / C++ Forum 7 14-Jan-2006 06:17
Operator overloading c++ clander CPP / C++ Forum 4 25-Apr-2005 09:21

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 23:44.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.