Jump to content

Matrix multiplication: Difference between revisions

add JavaScript
(Added Scala)
(add JavaScript)
Line 630:
return ans;
}</lang>
 
=={{header|JavaScript}}==
{{works with|SpiderMonkey}} for the print() function
<lang javascript>function Matrix(ary) {
this.mtx = ary
this.height = ary.length;
this.width = ary[0].length;
 
this.toString = function() {
var s = []
for (var i = 0; i < this.mtx.length; i++)
s.push( this.mtx[i].join(",") );
return s.join("\n");
}
 
this.mult = function(other) {
if (this.width != other.height) {
throw "error: incompatible sizes";
}
 
var result = [];
for (var i = 0; i < this.height; i++) {
result[i] = [];
for (var j = 0; j < other.width; j++) {
var sum = 0;
for (var k = 0; k < this.width; k++) {
sum += this.mtx[i][k] * other.mtx[k][j];
}
result[i][j] = sum;
}
}
return new Matrix(result);
}
}
 
var a = new Matrix([[1,2],[3,4]])
var b = new Matrix([[-3,-8,3],[-2,1,4]]);
print(a.mult(b));
</lang>
output
<pre>-7,-6,11
-17,-20,25</pre>
 
=={{header|Mathematica}}==
<lang mathematica>M1 = {{1, 2},
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.