Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,921 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,988 people online right now. Registration is fast and FREE... Join Now!




inverse matrix

 
Reply to this topicStart new topic

inverse matrix, full code for inverse matrix

koprivica
14 Dec, 2007 - 04:46 AM
Post #1

New D.I.C Head
*

Joined: 13 Dec, 2007
Posts: 8


My Contributions
Is there anybody who can give me idea about solving inverse matrix in c?

User is offlineProfile CardPM
+Quote Post

Bench
RE: Inverse Matrix
14 Dec, 2007 - 04:58 AM
Post #2

D.I.C Addict
Group Icon

Joined: 20 Aug, 2007
Posts: 686



Thanked: 24 times
Dream Kudos: 150
Expert In: C/C++

My Contributions
You obviously missed this as you came into the forum
http://www.dreamincode.net/forums/showtopic13117.htm

Please read the rules, and don't ask for other people to just spoon-feed you with complete solutions.

You might want to start out by writing a program which simply represents a matrix using arrays. Then look into ways of inverting matrices, and experiment with translating these into C code
http://en.wikipedia.org/wiki/Invertible_matrix

This post has been edited by Bench: 14 Dec, 2007 - 05:02 AM
User is offlineProfile CardPM
+Quote Post

koprivica
RE: Inverse Matrix
17 Dec, 2007 - 12:02 AM
Post #3

New D.I.C Head
*

Joined: 13 Dec, 2007
Posts: 8


My Contributions
I am very glad that you are so smart, but you didn't answer my question.

User is offlineProfile CardPM
+Quote Post

jjhaag
RE: Inverse Matrix
17 Dec, 2007 - 12:14 AM
Post #4

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
If your question remains that you want to be provided with the full code for inverting a matrix, the answer remains the same. We're not going to do your work for you, and you still haven't provided anything that shows you've made an effort on this yourself.

If you've made an attempt to implement this yourself, please post your code and we will be more than happy to help you move forward with it. If you haven't, there are a number of snippets available in the code database that have dealt with matrices and calculating their inverses. These should be helpful in getting you started.
User is offlineProfile CardPM
+Quote Post

nirvanarupali
RE: Inverse Matrix
17 Dec, 2007 - 12:23 AM
Post #5

D.I.C Stomach
Group Icon

Joined: 1 Aug, 2007
Posts: 995



Thanked: 4 times
Dream Kudos: 375
My Contributions
Dream.In.Code has a policy by which we prefer to see a good faith effort on your part before providing source code for homework assignments. Please post the code you have written in an effort to resolve the problem, and our members would be happy to provide some guidance. Be sure to include a description of any errors you are encountering as well.

Post your code like this:
code.gif
User is offlineProfile CardPM
+Quote Post

koprivica
RE: Inverse Matrix
27 Dec, 2007 - 01:17 PM
Post #6

New D.I.C Head
*

Joined: 13 Dec, 2007
Posts: 8


My Contributions
I am working with this for inverse matrix


CODE
#include <stdio.h>
#include <math.h>
#define NMAX 100

main()
{    double x [n][n];
    int i, j, a [n][n]={    1, 2, 3, 4, 5,
                                    6, 7, 8, 9, 10,
                                    11, 12, 13, 14, 15,
                                    16, 17, 18, 19, 20,
                                    21, 22, 23, 24, 25        };
    for(j=0; j<n; j++)
        printf("\t[%d]", j);
    for(i=0; i<n; i++)     {    printf("\n\na[%d]", i);
        for(j=0;j<n; j++)
            printf("\t%d", a[i][j]);
    }
    for(j=0; j<n; j++)
        printf("\t[%d]", j);
    for(i=0; i<n; i++)
    {    printf("\n\na[%d]", i);
        for(j=0;j<n; j++)
            printf("\t%d", x[i][j]=0);
    }
}
y= double migs (a, x, n, indx);

/* Function to invert matrix a[][] with the inverse stored
   in x[][] in the output.  
{
int indx[];
double a[n][n],x[n][n];
{
  int i,j,k;
  double b[n][n];
  void elgs();

  if (n > 6)
  {
    printf("The matrix dimension is too large.\n");
    exit(1);
  }

  for (i = 0; i < n; ++i)
  {
    for (j = 0; j < n; ++j)
    {
      b[i][j] = 0;
    }
  }
  for (i = 0; i < n; ++i)
  {
    b[i][i] = 1;
  }

  elgs (a,n,indx);

  for (i = 0; i < n-1; ++i)
  {
    for (j = i+1; j < n; ++j)
    {
      for (k = 0; k < n; ++k)
      {
        b[indx[j]][k] = b[indx[j]][k]-a[indx[j]][i]*b[indx[i]][k];
      }
    }
  }

for (i = 0; i < n; ++i)
  {
    x[n-1][i] = b[indx[n-1]][i]/a[indx[n-1]][n-1];
    for (j = n-2; j >= 0; j = j-1)
    {
      x[j][i] = b[indx[j]][i];
      for (k = j+1; k < n; ++k)
      {
        x[j][i] = x[j][i]-a[indx[j]][k]*x[k][i];
      }
      x[j][i] = x[j][i]/a[indx[j]][j];
    }
  }
}

void elgs (a,n,indx)

/* Function to perform the partial-pivoting Gaussian elimination.
   a[][] is the original matrix in the input and transformed
   matrix plus the pivoting element ratios below the diagonal
   in the output.  indx[] records the pivoting order.
  
{
int n;
int indx[];
double a[n][n];
{
  int i, j, k, itmp;
  double c1, pi, pi1, pj;
  double c[n];

  if (n > 6)
  {
    printf("The matrix dimension is too large.\n");
    exit(1);
  }

/* Initialize the index */

  for (i = 0; i < n; ++i)
  {
    indx[i] = i;
  }

/* Find the rescaling factors, one from each row */

  for (i = 0; i < n; ++i)
  {
    c1 = 0;
    for (j = 0; j < n; ++j)
    {
      if (fabs(a[i][j]) > c1) c1 = fabs(a[i][j]);
    }
    c[i] = c1;
  }

/* Search the pivoting (largest) element from each column */

  for (j = 0; j < n-1; ++j)
  {
    pi1 = 0;
    for (i = j; i < n; ++i)
    {
      pi = fabs(a[indx[i]][j])/c[indx[i]];
      if (pi > pi1)
      {
        pi1 = pi;
        k = i;
      }
    }

/* Interchange the rows via indx[] to record pivoting order */

    itmp = indx[j];
    indx[j] = indx[k];
    indx[k] = itmp;
    for (i = j+1; i < n; ++i)
    {
      pj = a[indx[i]][j]/a[indx[j]][j];

/* Record pivoting ratios below the diagonal */

      a[indx[i]][j] = pj;

/* Modify other elements accordingly */

      for (k = j+1; k < n; ++k)
      {
        a[indx[i]][k] = a[indx[i]][k]-pj*a[indx[j]][k];
      }
    }
  }
}


This is what I get after compiling code

Compiling...
code44.c
code44.c(42) : error C2059: syntax error : 'type'
code44.c(46) : error C2449: found '{' at file scope (missing function header?)
code44.c(178) : fatal error C1004: unexpected end of file found Error
executing cl.exe.

code44.obj - 3 error(s), 0 warning(s)

After this I can't find way to continue. Please, help me to remove this errors.
Thanks

This post has been edited by jjhaag: 27 Dec, 2007 - 02:44 PM
User is offlineProfile CardPM
+Quote Post

jjhaag
RE: Inverse Matrix
27 Dec, 2007 - 03:09 PM
Post #7

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
The formatting of this is all over the place, and it makes it incredibly difficult to figure out exactly what you're trying to do. My recommendation with this would be to start over with a new file, paying special attention to the layout of the function prototypes and their definitions. It appears that you are making several function declarations and definitons right in the middle of main(), which is going to cause problems.

It appears that you have two functions that you're trying to use here - migs() and elgs(). Start by laying out the prototypes and definitions properly with respect to the position of the main() routine:
CODE
#include <stdio.h>
#include <math.h>

double migs (double a[][], double x[][], int n, int indx);//  function prototype for migs()
void elgs (a[][], int n, int indx);//  function prototype for elgs()


int main() { //start of main()
    //code to declare and initialize variables
    //call functions, etc.
    //display results
    return 0;
} //end of main()


//  function definition for migs()
double migs (double a[][], double x[][], int n, int indx) {
    //code defining the procedure for migs()
}

//  function definition for elgs()
void elgs (a[][], int n, int indx) {
    //code defining the procedure for elgs()
}


Once you've got that, start filling in the code in the appropriate places. Sorry not to be of more help, but the organization of the original code precludes being able to actually figure out what you're trying to do in each sections.

And next time, please use the code tags when posting code, like this code.gif. It makes it way easier to read, as well as copying and pasting. It's been corrected in the above post, but keep it in mind for next time.


User is offlineProfile CardPM
+Quote Post

koprivica
RE: Inverse Matrix
3 Jan, 2008 - 01:35 PM
Post #8

New D.I.C Head
*

Joined: 13 Dec, 2007
Posts: 8


My Contributions
I am still working with some codes in C and C++ for getting inverse matrix.
Now, I have problem with compiling. I can find 'bits/types.h' to complite compiling of code for inverse matrix in C++.
Please, if somebody can help me with this. It will be best if you post a link or attach it with reply. Olso you can send file to me on: **(email address removed for spam prevention purposes)
Thanks

This post has been edited by jjhaag: 3 Jan, 2008 - 01:42 PM
User is offlineProfile CardPM
+Quote Post

koprivica
RE: Inverse Matrix
5 Jan, 2008 - 05:03 PM
Post #9

New D.I.C Head
*

Joined: 13 Dec, 2007
Posts: 8


My Contributions
CODE



#include <stdlib.h>
#include <iostream.h>

#include "matrix.h"

// allocate
void Matrix::allocate (){
    mat=new Type*[rows];
    for (int i=0;i<=rows;i++) {
        mat[i]=new Type[cols];
        for (int j=0;j<=cols;j++) mat[i][j]=Type(0);    
    }
}


// release
void Matrix::release (){
    for (int i=0;i<=rows;i++) delete [] mat[i];
    delete [] mat;
}


// copy matrix
void Matrix::copy (const Matrix& right){
    for (int i=0;i<=rows;i++)
        for (int j=0;j<=cols;j++) this->mat[i][j]=right.mat[i][j];
}



// constructor
Matrix::Matrix (int m, int n): rows(m), cols(n){
    allocate();
}


// copy constructor
Matrix::Matrix (const Matrix& right): rows(right.rows),cols(right.cols){
    allocate();
    copy(right);
}


// destructor
Matrix::~Matrix (){
    release ();
}


Matrix& Matrix:: operator = (const Matrix& right){
    if (&right==this) return *this;
    if (right.rows!=rows || right.cols!=cols) return *this;
    release();
    allocate();
    copy(right);
    return *this;
}


Type& Matrix::operator () (int i, int j) {
    static Type error(0);
    if (i<0 || i>rows || j<0 || j>cols) return error;
    return mat[i-1][j-1];
}


int operator == (const Matrix& left, const Matrix& right) {
    if (right.rows!=left.rows || right.cols!=left.cols) return 0;
    for (int i=0;i<=left.rows;i++)
        for (int j=0;j<=left.cols;j++)
            if (left.mat[i][j]!=right.mat[i][j]) return 0;
    return 1;
}


int operator != (const Matrix& left, const Matrix& right) {
    return !(left==right);
}


Matrix operator + (const Matrix& m) {return m;}


Matrix operator - (const Matrix& m) {return -Type(1)*m;}


Matrix operator + (const Matrix& left, const Matrix& right) {
    Matrix m=left;
    return m+=right;
}


Matrix operator - (const Matrix& left, const Matrix& right) {
    Matrix m=left;
    return m-=right;
}


Matrix& Matrix :: operator+= (const Matrix& right) {
    if (rows!=right.rows || cols!=right.cols) return *this;
    for (int i=0;i<rows;i++)
        for (int j=0;j<cols;j++)
            mat[i][j]+=right.mat[i][j];
    return *this;

}


Matrix& Matrix :: operator-= (const Matrix& right) {
    if (rows!=right.rows || cols!=right.cols) return *this;
    for (int i=0;i<rows;i++)
        for (int j=0;j<cols;j++)
            mat[i][j]-=right.mat[i][j];
    return *this;

}

    
Matrix operator * (const Matrix& left, const Matrix& right) {
    Matrix m (left.rows, right.cols);
    if (left.cols!=right.rows) return m;
    for (int i=0;i<left.rows;i++)
        for (int j=0;j<right.cols;j++)
            for (int k=0;k<left.cols;k++)
                m.mat[i][j]+=left.mat[i][k]*right.mat[k][j];
    return m;

}


Matrix& Matrix :: operator*= (const Type& t) {
    for (int i=0;i<rows;i++)
        for (int j=0;j<cols;j++)
            mat[i][j]*=t;
    return *this;
}

        

Matrix operator * (const Matrix& left, const Type& t){
    Matrix m=left;
    return m*=t;
}


Matrix operator * (const Type& t, const Matrix& right){
    return right*t;
}


Matrix& Matrix::operator *= (const Matrix& right) {
    return *this=*this*right;
}


istream& operator >> (istream& is, Matrix& m) {
    for (int i=0;i<m.rows;i++)
        for (int j=0;j<m.cols;j++)
            is>>m.mat[i][j];
    return is;
}


ostream& operator << (ostream& os, const Matrix& m) {
    os<<"{\n";
    for (int i=0;i<m.rows;i++) {
        os <<"{";
        for (int j=0;j<m.cols;j++)
            os << m.mat[i][j] << ((j<m.cols-1)?",":"}");
        os << ((i<m.rows-1)?",\n":"\n}\n");
    }
    return os;
}


// transpose matrix
Matrix trans (const Matrix& m) {
    Matrix temp(m.cols, m.rows);
    for (int i=0;i<m.rows;i++)
        for (int j=0;j<m.cols;j++)
            temp.mat[j][i]=m.mat[i][j];
    return temp;
}


// one row and col is out
Matrix compl (const Matrix& m, int r, int c) {
    Matrix temp(m.rows-1, m.cols-1);
    if (m.cols<1 || m.rows<1) return temp;
    for (int i=0,x=0;i<m.rows;i++) {
        if (i==r-1) continue;
        for (int j=0,y=0;j<m.cols;j++) {
            if (j==c-1) continue;
            temp.mat[x][y]=m.mat[i][j];
            y++;
        }
        x++;
    }
    return temp;
}


// det matrix
Type det (const Matrix& m) {
    if (m.rows!=m.cols) return 0;
    if (m.rows==1) return m.mat[0][0];
    Type temp=Type(0);
    for (int j=0,c=1;j<m.cols;j++,c*=-1)
        temp+=(Type(c)*m.mat[0][j]*det(compl(m,1,j+1)));
    return temp;
}


// cofact
Type cofact (const Matrix& m, int r, int c) {
    if (m.rows!=m.cols) return 0;
    if ((r+c)%2!=0)
        return (-det (compl(m,r,c)));
    else
        return (det (compl(m,r,c)));
}


// adj matrix
Matrix adj (const Matrix& m) {
    Matrix temp(m.rows, m.cols);
    if (m.rows!=m.cols) return temp;
    for (int i=0;i<m.rows;i++)
        for (int j=0;j<m.cols;j++)
            temp.mat[i][j]=cofact(m,i+1,j+1);
    return trans(temp);
}


// invers matrix
Matrix inv (const Matrix& m) {
    Type temp=det(m);
    if (temp!=0)
        return (1/temp)*adj(m);
    else
        return Matrix(0,0);
}

void main () {

#define NMAX 4

    Matrix m (NMAX,NMAX);

        cin>>m;


    
    const Matrix& m1=m;
    const Matrix m2=inv (m1);


cout<<"m="<<m2<<'\n';
}


Where:

CODE

// Modul matrix.h

#ifndef _Matrix
#define _Matrix

class istream;
class ostream;

typedef int Type;

class Matrix{
public:
    Matrix (int m, int n);
    Matrix (const Matrix& mat);
    ~Matrix ();

    Matrix& operator = (const Matrix&);

    friend int operator == (const Matrix&, const Matrix&);
    friend int operator != (const Matrix&, const Matrix&);
    Type& operator () (int i, int j);

    friend Matrix operator + (const Matrix&);
    friend Matrix operator - (const Matrix&);
    friend Matrix operator + (const Matrix&, const Matrix&);
    friend Matrix operator - (const Matrix&, const Matrix&);
    friend Matrix operator * (const Matrix&, const Matrix&);
    friend Matrix operator * (const Matrix&, const Type&);
    friend Matrix operator * (const Type&, const Matrix&);

    friend Matrix trans (const Matrix&);
    friend Matrix compl (const Matrix&, int i, int j);
    friend Type det (const Matrix&);
    friend Type cofact (const Matrix&, int i, int j);
    friend Matrix adj (const Matrix&);
    friend Matrix inv (const Matrix&);

    Matrix& operator += (const Matrix&);
    Matrix& operator -= (const Matrix&);
    Matrix& operator *= (const Matrix&);
    Matrix& operator *= (const Type&);


    friend istream& operator >> (istream&, Matrix&);
    friend ostream& operator << (ostream&, const Matrix&);

protected:
    void allocate ();
    void release ();
    void copy (const Matrix&);

private:
    int cols, rows;
    Type **mat;

};


#endif


You can also see doc file.
I can figure out what is problem with main function. It allow me to write elements of matrix but not to see what is hepenning in output. Can somebody help me with this?


Attached File(s)
Attached File  Matrix.doc ( 45k ) Number of downloads: 82
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 1/8/09 02:49PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month