Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I am currently trying to multiply two matrices in JavaScript and have written the following function:

JavaScript
MathHelper.multiplyMatrix = function(a, b) {
        if (a.length != b.length)
		return undefined;
	var result = [];
	var rowLength = Math.sqrt(a.length);
	for (i = 0; i < a.length; i++) {
		var index = parseInt(i / rowLength);
		var val = 0;
		for (var x = 0; x < rowLength; x++) {
		val += a[index * rowLength + x] * b[x * rowLength + (i % rowLength)];
		}
		result[i] = val;
	}
	return result;
};


I am new to matrices and was wonder if anyone knows of a more efficient way of doing this?

Regards,
Dom
Posted
Comments
Sergey Alexandrovich Kryukov 15-Nov-12 11:00am    
Why are you not using 2-dimensional arrays, [,]? Using a one-dimensional representation of 2-dimensional array is possible, but complicates indexing, like using % operator, etc.
--SA

I did not check up the code, but why not using 2-dimensional arrays which better fit the nature of a matrix and greatly simplify indexing? Just in case:
http://www.kavoir.com/2009/02/javascript-multi-dimensional-array.html[^].

—SA
 
Share this answer
 
Comments
DominicZA 15-Nov-12 11:12am    
I did use 2 dimensional arrays for my first solution. However, I am needing to do this because I am manipulating the matrix3d property in the webkitTransform. This was just easier for working with that
Sergey Alexandrovich Kryukov 15-Nov-12 11:18am    
I don't see how though. Multidimensional arrays are just natural for such applications..
--SA
Espen Harlinn 15-Nov-12 11:18am    
Good point :-)
Sergey Alexandrovich Kryukov 15-Nov-12 11:18am    
Thank you, Espen.
--SA
I think you're going to like Sylvester[^]

It's a vector, matrix and geometry library for JavaScript.

Best regards
Espen Harlinn
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 15-Nov-12 19:32pm    
Nice, a 5.
--SA
Espen Harlinn 15-Nov-12 19:34pm    
Thank you, Sergey :-D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900