Matrix Multiplication
amalfiCoast
Posts: 132
in Propeller 1
Hello,
I am trying to find an example of how to multiply two matrices (for example, two 3x3 matrices) in C. Does anyone know of any tutorials online that explain this? I know I have to use pointers but I'm having a hard time grasping how to do this task.
Thanks,
David
I am trying to find an example of how to multiply two matrices (for example, two 3x3 matrices) in C. Does anyone know of any tutorials online that explain this? I know I have to use pointers but I'm having a hard time grasping how to do this task.
Thanks,
David
Comments
https://codeitaway.wordpress.com/2012/01/26/c-program-to-multiply-two-matrix-multiplication-of-3x3-matrix-in-c/
Each element in the product of matrices is the sum of the products of the row and corresponding column, so this produce the output of the sum of 2 3x3 matrices. Not very efficient with 3 nested loops, though.
Thank you for your replies. Apologies for getting back so late - been busy. Below is a piece of code I was working on when I posted my original question. It looks like I had something similar to your responses in terms of the algorithm. I think my main problem is passing matrices to a function - a matrix multiply function in this case. Do you have to use pointers to pass arrays to functions, and if so, how can I do this?
Respectfully,
David
But, they have a lot of baggage would wouldn't fit in a microcontroller...
In C the name of an array is actually a pointer, so for
int a[10];
"a" is a pointer to int. int *.
Thank you so much for your help. I was able to get it working Microcontrolled mentioned that this approach is not efficient with 3 nested loops. Is there a "better" or more efficient way to do this? I may have some other questions as I work through some other matrix math functions. Thanks again! Here is the working code:
Respectfully,
David
I'm sure you can imagine that the line:
is executed 3 * 3 * 3 = 27 times as all those loops go around.
On each execution i, j, k have some value between 0 and 2.
So one optimization would be to get rid of all the loops and write out that line 27 times with the correct numbers instead of i, j and k.
That would get rid of all the instructions that do the loop jumping, incrementing and testing of i, j and k. It would just run through a straight line of 27 statements that are actually doing the work you want.
This kind of optimization is known as "loop unrolling".
That said, when loops are simple enough, modern compilers will do a lot of loop unrolling for you, so you might not see much gain (in an optimized build, at least).
Thank you for your detailed responses. This forum is great for someone like me.
Respectfully,
David
David, I'm sure I speak for many of us that it's a great place for us too !
- Howard