Matrix Multiplication again....

This is a discussion on Matrix Multiplication again.... within the C++ Programming forums, part of the General Programming Boards category; HI, This time i have already do some algorithm for the Matrix Multiplication. Here is my code(algorithm): for (i=0; i<rows_a; ...

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    56

    Unhappy Matrix Multiplication again....

    HI,
    This time i have already do some algorithm for the Matrix Multiplication.
    Here is my code(algorithm):

    for (i=0; i<rows_a; i++)
    for(j=0; j<cols_b; j++)
    {
    sum=0;
    for(k=0; k<cols_a; k++)
    sum+=(a[i][k]*b[k][j]);
    c[i][j]=sum;
    }


    But, the problem is, it is only limited to Square Matrix right???
    I would like to do all Matrix Multiplication not only Square Matrix...
    Can someone help me please?

  2. #2
    Registered User
    Join Date
    Jan 2002
    Posts
    552
    It looks like it will work for matrix multiplication of non-square matricies
    C Code. C Code Run. Run Code Run... Please!

    "Love is like a blackhole, you fall into it... then you get ripped apart"

  3. #3
    Registered User
    Join Date
    Jun 2002
    Posts
    82
    Hi-

    The code you have should work for non-square matrices. The only constraint is
    Code:
    (cols_a == rows_b)
    Then, based on the other dimensions of the a and b, you'll end up with a matrix that is rows_a x cols_b in size.

    Example:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main() {
       int rows_a = 3, rows_b = 3, cols_a = 3, cols_b = 2;
       int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, {7, 8, 9 } };
       int b[3][2] = { { 1, 2 }, {3, 4}, {5, 6} };
    
       int c[3][2];
    
       for (int i = 0; i < rows_a; i++) {
          for (int j = 0; j < cols_b; j++) {
             int sum = 0;
             for (int k = 0; k < cols_a; k++)
                sum += (a[i][k] * b[k][j]);
             c[i][j] = sum;
             cout << "c[ " << i << " ][ " << j << " ] = " << c[i][j] << endl;
          }
       }
    }
    Claus Hetzer
    Compiler: Borland 5.5 (on Windows)
    Solaris CC (on Unix)
    Known Languages: C++, MATLAB, Perl, Java

  4. #4
    Registered User
    Join Date
    Oct 2002
    Posts
    56
    Thanks everyone, i think that the code is actually work for non-square Matrix too.

    but, fot the program of geophyzzer
    it works, but i want to let the user input the Matrix instead just entering the matrix yourself....

    How could i do it?

  5. #5
    Registered User
    Join Date
    Oct 2002
    Posts
    56

    Wink

    Here is my code for matrix multiplication
    There are some place that i don't know how to do, and i put it in "?"

    Please help..

    #include <iostream.h>


    int main()
    {
    int rows_a, rows_b, cols_a, cols_b;
    cout<<"How many rows in a?";
    cin>>rows_a;
    cout<<"How many rows in b?";
    cin>>rows_b;
    cout<<"How many colons in a?";
    cin>>cols_a;
    cout<<"How many colons in b?";
    cin>>cols_b;
    int a[rows_a][cols_a] = {{???}};
    int b[rows_a][cols_b] = {{???}};

    int c[?][?];

    for (int i = 0; i < rows_a; i++)
    {
    for (int j = 0; j < cols_b; j++)
    {
    int sum = 0;
    for (int k = 0; k < cols_a; k++)
    sum += (a[i][k] * b[k][j]);
    c[i][j] = sum;
    cout << "c[ " << i << " ][ " << j << " ] = " << c[i][j] << endl;
    }
    }
    }

  6. #6
    Registered User
    Join Date
    Oct 2002
    Posts
    56

    Unhappy

    sorry everyone, i have put tags for my code, but i don't know why it doesn't work when i paste it in this board....

  7. #7
    Registered User
    Join Date
    Jun 2002
    Posts
    82
    Well, there's a couple of ways, depending on how advanced (and C++ish) you want the code to look

    1) Have dynamically allocated matrices, which allows you to input the dimensions at run-time. Then, prompt the user for the elements of the matrices and read them in using cin >>. If you don't use dynamic allocation (i.e. "new" and "delete") then you have to hard-code the matrix dimensions at compile-time. The main problem with this is I think dynamically allocating a 2-d array can be tricky; I haven't done it but probably someone else here can describe the most efficient way. This is the "C" approach, and probably the easiest if you don't know classes or the STL.

    2) Use vector< vector< float> > instead of arrays. This has the advantage of not having to worry about dynamic memory allocation, but the code can be kind of hard to keep track of. This is the "C++ syntax but C style" solution (i.e. not object-oriented but uses C++ syntax and the STL) and its probably the first way that I would consider if I were designing the program as a one-shot project.

    3) Create a Matrix class and write the dynamic allocation there or use a vector. The advantage is that you can set the matrix up as a 1-dimensional array and calculate based on the 2-d coordinates where the element lives in your 1-d array. For example, if the user wanted to have a nRowsxnCols matrix, you could allocate a 15-element array or vector:
    Code:
    float *matrixPtr = new float[ nRows * nCols ];
    // or
    vector< float > matrix( nRows * nCols );
    then if the user wanted to refer to element [row,col] you could calculate:
    Code:
    float element = matrixPtr[ (row-1)*nCols + (col-1) ];
    // or
    float element = matrix.at( (row-1)*nCols + (col-1) );
    This is the way to go if you really want to learn about C++, as it incorporates class definitions, member functions, data encapsulation, dynamic memory allocation, the STL, operator overloading, etc. Probably a good way would be #1 above for right now, then work on #3 as an ongoing project. The folks here will be more than happy to help out as long as it looks like you are doing most of the work yourself and you have very specific questions.
    Claus Hetzer
    Compiler: Borland 5.5 (on Windows)
    Solaris CC (on Unix)
    Known Languages: C++, MATLAB, Perl, Java

  8. #8
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Here's my code for matrix multiplication, notice that the size of the matrices is checked compile-time.
    This is actually the beginning of a templated matrix class.

    Code:
    template<int rows, int cols, typename T=double>
    class matrix
    {
        public:   
            T& operator()(int r, int c)
            {
                return data[r-1][c-1];
            } 
            
        private:
            T data[rows][cols];
    };
    
    
    template<int rowsA, int colsA, int colsB, typename typeA, typename typeB>
    matrix<rowsA,colsB,typeA> operator*( matrix<rowsA,colsA,typeA> A, matrix<colsA,colsB,typeB> B )
    {
        matrix<rowsA,colsB,typeA> C;
        
        //For each element in C
        for (int currentCRow = 1; currentCRow <= rowsA; ++currentCRow)
            for (int currentCCol = 1; currentCCol <= colsB; ++currentCCol)
            {
                typeA sum = 0;
                for (int n=1; n <= colsA; ++n)
                    sum += A(currentCRow,n) * B(n,currentCCol);
                C(currentCRow,currentCCol) = sum;
            }
            
        return C;
    }
                    
    template<int rows, int cols, typename T>
    std::ostream& operator<<(std::ostream& out, matrix<rows,cols,T> M)
    {
        for (int r=1;r<=rows;++r)
        {
            out << "(";
            for (int c=1;c<cols;++c)
                out << M(r,c) << ",";
            out << M(r,cols) << ")\n";
        }
        return out;
    }
    Some example code
    Code:
    int main()
    {
        matrix<2,3> A;
        matrix<3,2> B;
        
        A(1,1)=1;A(1,2)=2;A(1,3)=3;
        A(2,1)=4;A(2,2)=5;A(2,3)=6;
    
        B(1,1)=7;B(1,2)=8;
        B(2,1)=9;B(2,2)=0;
        B(3,1)=1;B(3,2)=2;
    
        //     (1 2 3)
        // A = (4 5 6)
        
        //     (7 8)
        // B = (9 0)
        //     (1 2)
        
        cout << A*B;
    }
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C - access violation
    By uber in forum C Programming
    Replies: 2
    Last Post: 07-08-2009, 02:30 PM
  2. *operator overloading: scalar matrix multiplication
    By gemini_shooter in forum C++ Programming
    Replies: 4
    Last Post: 06-08-2009, 02:14 PM
  3. Matrix Multiplication ( Accessing data from a file ) HELP
    By six_degreez in forum C Programming
    Replies: 2
    Last Post: 07-24-2008, 06:21 PM
  4. Matrix Help
    By HelpmeMark in forum C++ Programming
    Replies: 27
    Last Post: 03-06-2008, 05:57 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21