Skip to content

Instantly share code, notes, and snippets.

@kevinfjbecker
Created August 12, 2011 14:22
Show Gist options
  • Save kevinfjbecker/1142131 to your computer and use it in GitHub Desktop.
Save kevinfjbecker/1142131 to your computer and use it in GitHub Desktop.
An example of Matrix mulitplication in JavaScript
<!DOCTYPE html>
<html>
<!--
Created using JS Bin
Source can be edited via /aludec/latest/edit
-->
<head>
<meta charset=utf-8 />
<title>Matrix Multiply</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<p id="hello">Hello World</p>
<script>
var getMatrix = (function(){
var toString = function(f){
return f ? f(this) : 'matrix';
};
var multiply = function(m){
var a = [[0,0,0],[0,0,0],[0,0,0]];
var i, j, k;
for(i = 0; i < 3; i += 1) {
for(j = 0; j < 3; j += 1) {
for(k = 0; k < 3; k += 1) {
a[i][j] += this.a[k][i] * m.a[j][k];
}
}
}
return getMatrix(a);
};
return function getMatrix(a) {
return {
'a': a,
'multiply': multiply,
'toString': toString
};
};
}());
var htmlStringify = function(m) {
var s = '';
s = s + '[' + m.a[0][0] + ', ' + m.a[0][1] + ', ' + m.a[0][2] + ']';
s = s + '</br>';
s = s + '[' + m.a[1][0] + ', ' + m.a[1][1] + ', ' + m.a[1][2] + ']';
s = s + '</br>';
s = s + '[' + m.a[2][0] + ', ' + m.a[2][1] + ', ' + m.a[2][2] + ']';
return s;
};
var cos = Math.cos(Math.PI / 4);
var sin = Math.sin(Math.PI / 4);
var m = getMatrix([
[ cos, sin, 0],
[-sin, cos, 0],
[ 0 , 0 , 1]
]);
var n = getMatrix([
[cos, -sin, 0],
[sin, cos, 0],
[ 0 , 0 , 1]
]);
var x = m.multiply(n);
document.getElementById('hello').innerHTML = x.toString(htmlStringify);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment