Thread: How do I multiply two square matrices by 1 nested loop?

  1. #1
    Registered User
    Join Date
    Dec 2019
    Posts
    17

    How do I multiply two square matrices by 1 nested loop?

    I managed to print the matrix in one loop, but how can I multiply two matrices in 2 loops (1 nested loop), please help!!

    Code:
    #include<iostream>
    using namespace std;
    #define size 4
    int main()
    {
      int M[size][size] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
      int *ptrMatris = &M[0][0];
      for (int i = 1; i <= 16; i++) {
        cout << *ptrMatris++ << " ";
        if (i % size == 0)
          cout << endl;
      }
      return 0;
    }
    Last edited by Salem; 04-19-2020 at 09:06 AM. Reason: Removed whacked apple font madness

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    679
    This way?
    Code:
    void m4x4_mult( double *m, double *n, double *r )
    {
      int i, j;
    
      for ( i = 0; i < 4; i++ )
        for ( j = 0; j < 4; j++ )
        {
          r[i+4*j] = m[4*j]   * n[i]   +
                     m[4*j+1] * n[i+4] +
                     m[4*j+2] * n[i+8] +
                     m[4*j+3] * n[i+12];
        }
    }

  3. #3
    Registered User
    Join Date
    Dec 2019
    Posts
    17
    yes, this way works but how can i write for any value of 0-10 not only 4. thanks... )

  4. #4
    Registered User
    Join Date
    Feb 2019
    Posts
    679
    You'll need a third loop for a variable square matrix dimensions...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C program multiply matrices
    By YannB in forum C Programming
    Replies: 10
    Last Post: 11-15-2013, 12:06 AM
  2. Replies: 19
    Last Post: 10-01-2013, 10:54 PM
  3. how many ways exists in order to multiply n matrices?
    By Amin sma in forum C++ Programming
    Replies: 7
    Last Post: 03-30-2012, 02:32 AM
  4. 2 Matrices multiply problem
    By ydan87 in forum C Programming
    Replies: 1
    Last Post: 01-22-2012, 12:48 AM
  5. how to multiply 2 matrices
    By newguy in forum C Programming
    Replies: 1
    Last Post: 10-29-2001, 03:48 AM

Tags for this Thread