You're here: Snippet Directory » C/C++ (495)
Language:

Matrix Multiplier

Language: English
Programming Language: C
Published by: foxxtrot713 [not registered]
Last Update: 5/15/2006
Views: 143


Description

C Code capable of multiplying out two matrices of any size. Relatively fast, but I wouldn't use it for say 3D Game engines.

Code

1 /* 2 * matrxmult - A function to Multiply Matrices 3 * 4 * Jeff Craig 5 * foxxtrot713 on SourceForge 6 * 7 * Version 0.1 Coded on 5-2-2000 8 * Version 0.9 Completed 7-29-2000 9 * Loop needs to be Documented 10 */ 11 12 #include <stdio.h> 13 #include <stdlib.h> 14 15 typedef struct MATRIX_TAG 16 { 17 float matrix[20][20]; 18 unsigned int rows; 19 unsigned int columns; 20 } MATRIX, *MATRIX_PTR; 21 22 MATRIX_PTR matrix_multiply( MATRIX_PTR first, MATRIX_PTR second) 23 { 24 MATRIX_PTR solution; 25 int sy, fx, fy, sx, x, y; 26 27 solution = (MATRIX_PTR)malloc(sizeof(MATRIX)); 28 29 if (first->columns != second->rows) { 30 printf("Number of Columns on first Matrix does not equal\nnumber of rows on Second Matrix.\n"); 31 return NULL; 32 } 33 x = y = 0; 34 35 solution->rows = first->rows; 36 solution->columns = second->columns; 37 38 /* This is the loop that actually multiplies out the matrices 39 * I wrote this code almost 2 months ago, and actually got it right 40 * As of this release I have not felt like documenting how it works, 41 * just thinking about it gives me a headache. If anyone wants to 42 * document it, feel free, and then e-mail it to me so I can put it 43 * into my code and distribute it. 44 * 45 * This code is actually pretty fast for how general it is. However, 46 * I wouldn't recommend it's use on software that is speed intensive 47 * (like 3D graphics), for those programs it is well worth writing 48 * code specific to your needs. 49 */ 50 51 for (fx=0; fx< second->columns;fx++) { 52 for (sy=0;sy<first->rows;sy++) { 53 for(fy=0;fy<first->columns;fy++) { 54 for (sx= 0; sx< second->rows; sx++) { 55 solution->matrix[x][y] += first->matrix[fx][fy] * second->matrix[sx][sy]; 56 } 57 } 58 y++; 59 if(y==solution->columns) 60 y=0; 61 } 62 x++; 63 if(x==solution->rows) 64 x=0; 65 } 66 67 return(solution); 68 }

No comments avaiable

Add a comment

Name *  

Email (won't be displayed) *    

Website  

Comment *  

Sicherheitscode Security Code *    

RSS