How to multiply 2 arrays (aka Matrix)

I was trying to make an array multiplication function but got some weird compilation error.

Basically the function should input two arrays where array A number of columns equal array B number of rows and output the result pointing to another array.

Here's the function:

float mul( float MatrixA, float MatrixB, int rowA, int colA, int colB, float* MatrixOut )
{
  for(int a; a < rowA; a++)
  {
    for(int b; b < colB; b++)
    {
      float sum = 0;
      for(int c; c < colA; c++) { sum += MatrixA[a][c] * MatrixB[c][b]; }
      *MatrixOut[a][b] = sum;
    }
  }
}

Error message:

Matrix:37: error: invalid types 'float[int]' for array subscript

       for(int c; c < colA; c++) { *MatrixOut[a][b] += MatrixA[a][c] * MatrixB[c][b]; }

                                                                                ^

exit status 1
invalid types 'float[int]' for array subscript

your function declaration says you are passing in two floats, not two pointers to floats as your input matrices.

for(int a; oops

You need to initialize the values of the for index :

 for(int a=0; a < rowA; a++)

and your function should be declared as void

Ok, so how can I pass matrices into the function?

void mul( float MatrixA, float MatrixB, int rowA, int colA, int colB, float* MatrixOut )
{
  for(int a=0; a < rowA; a++)
  {
    for(int b=0; b < colB; b++)
    {
      for(int c=0; c < colA; c++) { *MatrixOut[a][b] += MatrixA[a][c] * MatrixB[c][b]; }
    }
  }
}

Look carefully at MatrixOut for clues.

If you use multiple array indicies, you'll need multiple levels of pointers/indirect.

I'd advise not to do it that way in C, just use pointer arithmetic and a single level of indirection like
this:

matrix [row * NCOLS + col]

AWOL:
Look carefully at MatrixOut for clues.

Well, there's always a first time :wink: Honestly don't know all the working mechanism and semantics behind pointers.

But I get, need to add "*" before the variable name. But don't have to use it when I call the variable? like described here & - Arduino Reference

MarkT:
If you use multiple array indicies, you'll need multiple levels of pointers/indirect.

I'd advise not to do it that way in C, just use pointer arithmetic and a single level of indirection like
this:

matrix [row * NCOLS + col]

Thanks that is a good tip.

Now the function compiles without errors, but is it OK?

void mul( float *MatrixA, float *MatrixB, int rowA, int colA, int colB, float *MatrixOut )
{
  for(int a=0; a < rowA; a++)
  {
    for(int b=0; b < colB; b++)
    {
      for(int c=0; c < colA; c++) { MatrixOut[a*colB+b] += MatrixA[a*colA+c] * MatrixB[c*colB+b]; }
    }
  }
}

// Assuming I use single-dimension arrays for matrices

Just test it with a few examples and see if you get the correct results