A-M baby
This commit is contained in:
parent
764da6cbbb
commit
db842d013d
19005 changed files with 197040 additions and 7 deletions
1
Task/Matrix-multiplication/0DESCRIPTION
Normal file
1
Task/Matrix-multiplication/0DESCRIPTION
Normal file
|
|
@ -0,0 +1 @@
|
|||
Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
|
||||
2
Task/Matrix-multiplication/1META.yaml
Normal file
2
Task/Matrix-multiplication/1META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
note: Matrices
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
MODE FIELD = LONG REAL; # field type is LONG REAL #
|
||||
INT default upb:=3;
|
||||
MODE VECTOR = [default upb]FIELD;
|
||||
MODE MATRIX = [default upb,default upb]FIELD;
|
||||
|
||||
# crude exception handling #
|
||||
PROC VOID raise index error := VOID: GOTO exception index error;
|
||||
|
||||
# define the vector/matrix operators #
|
||||
OP * = (VECTOR a,b)FIELD: ( # basically the dot product #
|
||||
FIELD result:=0;
|
||||
IF LWB a/=LWB b OR UPB a/=UPB b THEN raise index error FI;
|
||||
FOR i FROM LWB a TO UPB a DO result+:= a[i]*b[i] OD;
|
||||
result
|
||||
);
|
||||
|
||||
OP * = (VECTOR a, MATRIX b)VECTOR: ( # overload vector times matrix #
|
||||
[2 LWB b:2 UPB b]FIELD result;
|
||||
IF LWB a/=LWB b OR UPB a/=UPB b THEN raise index error FI;
|
||||
FOR j FROM 2 LWB b TO 2 UPB b DO result[j]:=a*b[,j] OD;
|
||||
result
|
||||
);
|
||||
# this is the task portion #
|
||||
OP * = (MATRIX a, b)MATRIX: ( # overload matrix times matrix #
|
||||
[LWB a:UPB a, 2 LWB b:2 UPB b]FIELD result;
|
||||
IF 2 LWB a/=LWB b OR 2 UPB a/=UPB b THEN raise index error FI;
|
||||
FOR k FROM LWB result TO UPB result DO result[k,]:=a[k,]*b OD;
|
||||
result
|
||||
);
|
||||
|
||||
# Some sample matrices to test #
|
||||
test:(
|
||||
MATRIX a=((1, 1, 1, 1), # matrix A #
|
||||
(2, 4, 8, 16),
|
||||
(3, 9, 27, 81),
|
||||
(4, 16, 64, 256));
|
||||
|
||||
MATRIX b=(( 4 , -3 , 4/3, -1/4 ), # matrix B #
|
||||
(-13/3, 19/4, -7/3, 11/24),
|
||||
( 3/2, -2 , 7/6, -1/4 ),
|
||||
( -1/6, 1/4, -1/6, 1/24));
|
||||
|
||||
MATRIX prod = a * b; # actual multiplication example of A x B #
|
||||
|
||||
FORMAT real fmt = $g(-6,2)$; # width of 6, with no '+' sign, 2 decimals #
|
||||
PROC real matrix printf= (FORMAT real fmt, MATRIX m)VOID:(
|
||||
FORMAT vector fmt = $"("n(2 UPB m-1)(f(real fmt)",")f(real fmt)")"$;
|
||||
FORMAT matrix fmt = $x"("n(UPB m-1)(f(vector fmt)","lxx)f(vector fmt)");"$;
|
||||
# finally print the result #
|
||||
printf((matrix fmt,m))
|
||||
);
|
||||
|
||||
# finally print the result #
|
||||
print(("Product of a and b: ",new line));
|
||||
real matrix printf(real fmt, prod)
|
||||
EXIT
|
||||
|
||||
exception index error:
|
||||
putf(stand error, $x"Exception: index error."l$)
|
||||
)
|
||||
10
Task/Matrix-multiplication/APL/matrix-multiplication.apl
Normal file
10
Task/Matrix-multiplication/APL/matrix-multiplication.apl
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
x ← +.×
|
||||
|
||||
A ← ↑A*¨⊂A←⍳4 ⍝ Same A as in other examples (1 1 1 1⍪ 2 4 8 16⍪ 3 9 27 81,[0.5] 4 16 64 256)
|
||||
B ← ⌹A ⍝ Matrix inverse of A
|
||||
|
||||
'F6.2' ⎕FMT A x B
|
||||
1.00 0.00 0.00 0.00
|
||||
0.00 1.00 0.00 0.00
|
||||
0.00 0.00 1.00 0.00
|
||||
0.00 0.00 0.00 1.00
|
||||
31
Task/Matrix-multiplication/Ada/matrix-multiplication-1.ada
Normal file
31
Task/Matrix-multiplication/Ada/matrix-multiplication-1.ada
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
with Ada.Text_IO; use Ada.Text_IO;
|
||||
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
|
||||
|
||||
procedure Matrix_Product is
|
||||
|
||||
procedure Put (X : Real_Matrix) is
|
||||
type Fixed is delta 0.01 range -100.0..100.0;
|
||||
begin
|
||||
for I in X'Range (1) loop
|
||||
for J in X'Range (2) loop
|
||||
Put (Fixed'Image (Fixed (X (I, J))));
|
||||
end loop;
|
||||
New_Line;
|
||||
end loop;
|
||||
end Put;
|
||||
|
||||
A : constant Real_Matrix :=
|
||||
( ( 1.0, 1.0, 1.0, 1.0),
|
||||
( 2.0, 4.0, 8.0, 16.0),
|
||||
( 3.0, 9.0, 27.0, 81.0),
|
||||
( 4.0, 16.0, 64.0, 256.0)
|
||||
);
|
||||
B : constant Real_Matrix :=
|
||||
( ( 4.0, -3.0, 4.0/3.0, -1.0/4.0 ),
|
||||
(-13.0/3.0, 19.0/4.0, -7.0/3.0, 11.0/24.0),
|
||||
( 3.0/2.0, -2.0, 7.0/6.0, -1.0/4.0 ),
|
||||
( -1.0/6.0, 1.0/4.0, -1.0/6.0, 1.0/24.0)
|
||||
);
|
||||
begin
|
||||
Put (A * B);
|
||||
end Matrix_Product;
|
||||
26
Task/Matrix-multiplication/Ada/matrix-multiplication-2.ada
Normal file
26
Task/Matrix-multiplication/Ada/matrix-multiplication-2.ada
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
package Matrix_Ops is
|
||||
type Matrix is array (Natural range <>, Natural range <>) of Float;
|
||||
function "*" (Left, Right : Matrix) return Matrix;
|
||||
end Matrix_Ops;
|
||||
|
||||
package body Matrix_Ops is
|
||||
---------
|
||||
-- "*" --
|
||||
---------
|
||||
function "*" (Left, Right : Matrix) return Matrix is
|
||||
Temp : Matrix(Left'Range(1), Right'Range(2)) := (others =>(others => 0.0));
|
||||
begin
|
||||
if Left'Length(2) /= Right'Length(1) then
|
||||
raise Constraint_Error;
|
||||
end if;
|
||||
|
||||
for I in Left'range(1) loop
|
||||
for J in Right'range(2) loop
|
||||
for K in Left'range(2) loop
|
||||
Temp(I,J) := Temp(I,J) + Left(I, K)*Right(K, J);
|
||||
end loop;
|
||||
end loop;
|
||||
end loop;
|
||||
return Temp;
|
||||
end "*";
|
||||
end Matrix_Ops;
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
Matrix("b"," ; rows separated by ","
|
||||
, 1 2 ; entries separated by space or tab
|
||||
, 2 3
|
||||
, 3 0")
|
||||
MsgBox % "B`n`n" MatrixPrint(b)
|
||||
Matrix("c","
|
||||
, 1 2 3
|
||||
, 3 2 1")
|
||||
MsgBox % "C`n`n" MatrixPrint(c)
|
||||
|
||||
MatrixMul("a",b,c)
|
||||
MsgBox % "B * C`n`n" MatrixPrint(a)
|
||||
|
||||
MsgBox % MatrixMul("x",b,b)
|
||||
|
||||
|
||||
Matrix(_a,_v) { ; Matrix structure: m_0_0 = #rows, m_0_1 = #columns, m_i_j = element[i,j], i,j > 0
|
||||
Local _i, _j = 0
|
||||
Loop Parse, _v, `,
|
||||
If (A_LoopField != "") {
|
||||
_i := 0, _j ++
|
||||
Loop Parse, A_LoopField, %A_Space%%A_Tab%
|
||||
If (A_LoopField != "")
|
||||
_i++, %_a%_%_i%_%_j% := A_LoopField
|
||||
}
|
||||
%_a% := _a, %_a%_0_0 := _j, %_a%_0_1 := _i
|
||||
}
|
||||
MatrixPrint(_a) {
|
||||
Local _i = 0, _t
|
||||
Loop % %_a%_0_0 {
|
||||
_i++
|
||||
Loop % %_a%_0_1
|
||||
_t .= %_a%_%A_Index%_%_i% "`t"
|
||||
_t .= "`n"
|
||||
}
|
||||
Return _t
|
||||
}
|
||||
MatrixMul(_a,_b,_c) {
|
||||
Local _i = 0, _j, _k, _s
|
||||
If (%_b%_0_0 != %_c%_0_1)
|
||||
Return "ERROR: inner dimensions " %_b%_0_0 " != " %_c%_0_1
|
||||
%_a% := _a, %_a%_0_0 := %_b%_0_0, %_a%_0_1 := %_c%_0_1
|
||||
Loop % %_c%_0_1 {
|
||||
_i++, _j := 0
|
||||
Loop % %_b%_0_0 {
|
||||
_j++, _k := _s := 0
|
||||
Loop % %_b%_0_1
|
||||
_k++, _s += %_b%_%_k%_%_j% * %_c%_%_i%_%_k%
|
||||
%_a%_%_i%_%_j% := _s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
DIM matrix1(3,1), matrix2(1,2), product(3,2)
|
||||
|
||||
matrix1() = 1, 2, \
|
||||
\ 3, 4, \
|
||||
\ 5, 6, \
|
||||
\ 7, 8
|
||||
|
||||
matrix2() = 1, 2, 3, \
|
||||
\ 4, 5, 6
|
||||
|
||||
product() = matrix1() . matrix2()
|
||||
|
||||
FOR row% = 0 TO DIM(product(),1)
|
||||
FOR col% = 0 TO DIM(product(),2)
|
||||
PRINT product(row%,col%),;
|
||||
NEXT
|
||||
PRINT
|
||||
NEXT
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
blsq ) {{1 2}{3 4}{5 6}{7 8}}{{1 2 3}{4 5 6}}mmsp
|
||||
9 12 15
|
||||
19 26 33
|
||||
29 40 51
|
||||
39 54 69
|
||||
21
Task/Matrix-multiplication/C++/matrix-multiplication-1.cpp
Normal file
21
Task/Matrix-multiplication/C++/matrix-multiplication-1.cpp
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
#include <iostream>
|
||||
#include <blitz/tinymat.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
using namespace blitz;
|
||||
|
||||
TinyMatrix<double,3,3> A, B, C;
|
||||
|
||||
A = 1, 2, 3,
|
||||
4, 5, 6,
|
||||
7, 8, 9;
|
||||
|
||||
B = 1, 0, 0,
|
||||
0, 1, 0,
|
||||
0, 0, 1;
|
||||
|
||||
C = product(A, B);
|
||||
|
||||
std::cout << C << std::endl;
|
||||
}
|
||||
36
Task/Matrix-multiplication/C++/matrix-multiplication-2.cpp
Normal file
36
Task/Matrix-multiplication/C++/matrix-multiplication-2.cpp
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
#include <iostream>
|
||||
#include "matrix.h"
|
||||
|
||||
#if !defined(ARRAY_SIZE)
|
||||
#define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
|
||||
#endif
|
||||
|
||||
int main() {
|
||||
int am[2][3] = {
|
||||
{1,2,3},
|
||||
{4,5,6},
|
||||
};
|
||||
int bm[3][2] = {
|
||||
{1,2},
|
||||
{3,4},
|
||||
{5,6}
|
||||
};
|
||||
|
||||
Matrix<int> a(ARRAY_SIZE(am), ARRAY_SIZE(am[0]), am[0], ARRAY_SIZE(am)*ARRAY_SIZE(am[0]));
|
||||
Matrix<int> b(ARRAY_SIZE(bm), ARRAY_SIZE(bm[0]), bm[0], ARRAY_SIZE(bm)*ARRAY_SIZE(bm[0]));
|
||||
Matrix<int> c;
|
||||
|
||||
try {
|
||||
c = a * b;
|
||||
for (unsigned int i = 0; i < c.rowNum(); i++) {
|
||||
for (unsigned int j = 0; j < c.colNum(); j++) {
|
||||
std::cout << c[i][j] << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
} catch (MatrixException& e) {
|
||||
std::cerr << e.message() << std::endl;
|
||||
return e.errorCode();
|
||||
}
|
||||
|
||||
} /* main() */
|
||||
177
Task/Matrix-multiplication/C++/matrix-multiplication-3.cpp
Normal file
177
Task/Matrix-multiplication/C++/matrix-multiplication-3.cpp
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
#ifndef _MATRIX_H
|
||||
#define _MATRIX_H
|
||||
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#define MATRIX_ERROR_CODE_COUNT 5
|
||||
#define MATRIX_ERR_UNDEFINED "1 Undefined exception!"
|
||||
#define MATRIX_ERR_WRONG_ROW_INDEX "2 The row index is out of range."
|
||||
#define MATRIX_ERR_MUL_ROW_AND_COL_NOT_EQUAL "3 The row number of second matrix must be equal with the column number of first matrix!"
|
||||
#define MATRIX_ERR_MUL_ROW_AND_COL_BE_GREATER_THAN_ZERO "4 The number of rows and columns must be greater than zero!"
|
||||
#define MATRIX_ERR_TOO_FEW_DATA "5 Too few data in matrix."
|
||||
|
||||
class MatrixException {
|
||||
private:
|
||||
std::string message_;
|
||||
int errorCode_;
|
||||
public:
|
||||
MatrixException(std::string message = MATRIX_ERR_UNDEFINED);
|
||||
|
||||
inline std::string message() {
|
||||
return message_;
|
||||
};
|
||||
|
||||
inline int errorCode() {
|
||||
return errorCode_;
|
||||
};
|
||||
};
|
||||
|
||||
MatrixException::MatrixException(std::string message) {
|
||||
errorCode_ = MATRIX_ERROR_CODE_COUNT + 1;
|
||||
std::stringstream ss(message);
|
||||
ss >> errorCode_;
|
||||
if (errorCode_ < 1) {
|
||||
errorCode_ = MATRIX_ERROR_CODE_COUNT + 1;
|
||||
}
|
||||
std::string::size_type pos = message.find(' ');
|
||||
if (errorCode_ <= MATRIX_ERROR_CODE_COUNT && pos != std::string::npos) {
|
||||
message_ = message.substr(pos + 1);
|
||||
} else {
|
||||
message_ = message + " (This an unknown and unsupported exception!)";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic class for matrices.
|
||||
*/
|
||||
template <class T>
|
||||
class Matrix {
|
||||
private:
|
||||
std::vector<T> v; // the data of matrix
|
||||
unsigned int m; // the number of rows
|
||||
unsigned int n; // the number of columns
|
||||
protected:
|
||||
|
||||
virtual void clear() {
|
||||
v.clear();
|
||||
m = n = 0;
|
||||
}
|
||||
public:
|
||||
|
||||
Matrix() {
|
||||
clear();
|
||||
}
|
||||
Matrix(unsigned int, unsigned int, T* = 0, unsigned int = 0);
|
||||
Matrix(unsigned int, unsigned int, const std::vector<T>&);
|
||||
|
||||
virtual ~Matrix() {
|
||||
clear();
|
||||
}
|
||||
Matrix& operator=(const Matrix&);
|
||||
std::vector<T> operator[](unsigned int) const;
|
||||
Matrix operator*(const Matrix&);
|
||||
|
||||
inline unsigned int rowNum() const {
|
||||
return m;
|
||||
}
|
||||
|
||||
inline unsigned int colNum() const {
|
||||
return n;
|
||||
}
|
||||
|
||||
inline unsigned int size() const {
|
||||
return v.size();
|
||||
}
|
||||
|
||||
inline void add(const T& t) {
|
||||
v.push_back(t);
|
||||
}
|
||||
};
|
||||
|
||||
template <class T>
|
||||
Matrix<T>::Matrix(unsigned int row, unsigned int col, T* data, unsigned int dataLength) {
|
||||
clear();
|
||||
if (row > 0 && col > 0) {
|
||||
m = row;
|
||||
n = col;
|
||||
unsigned int mxn = m * n;
|
||||
if (dataLength && data) {
|
||||
for (unsigned int i = 0; i < dataLength && i < mxn; i++) {
|
||||
v.push_back(data[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <class T>
|
||||
Matrix<T>::Matrix(unsigned int row, unsigned int col, const std::vector<T>& data) {
|
||||
clear();
|
||||
if (row > 0 && col > 0) {
|
||||
m = row;
|
||||
n = col;
|
||||
unsigned int mxn = m * n;
|
||||
if (data.size() > 0) {
|
||||
for (unsigned int i = 0; i < mxn && i < data.size(); i++) {
|
||||
v.push_back(data[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template<class T>
|
||||
Matrix<T>& Matrix<T>::operator=(const Matrix<T>& other) {
|
||||
clear();
|
||||
if (other.m > 0 && other.n > 0) {
|
||||
m = other.m;
|
||||
n = other.n;
|
||||
unsigned int mxn = m * n;
|
||||
for (unsigned int i = 0; i < mxn && i < other.size(); i++) {
|
||||
v.push_back(other.v[i]);
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
std::vector<T> Matrix<T>::operator[](unsigned int index) const {
|
||||
std::vector<T> result;
|
||||
if (index >= m) {
|
||||
throw MatrixException(MATRIX_ERR_WRONG_ROW_INDEX);
|
||||
} else if ((index + 1) * n > size()) {
|
||||
throw MatrixException(MATRIX_ERR_TOO_FEW_DATA);
|
||||
} else {
|
||||
unsigned int begin = index * n;
|
||||
unsigned int end = begin + n;
|
||||
for (unsigned int i = begin; i < end; i++) {
|
||||
result.push_back(v[i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
Matrix<T> Matrix<T>::operator*(const Matrix<T>& other) {
|
||||
Matrix result(m, other.n);
|
||||
if (n != other.m) {
|
||||
throw MatrixException(MATRIX_ERR_MUL_ROW_AND_COL_NOT_EQUAL);
|
||||
} else if (m <= 0 || n <= 0 || other.n <= 0) {
|
||||
throw MatrixException(MATRIX_ERR_MUL_ROW_AND_COL_BE_GREATER_THAN_ZERO);
|
||||
} else if (m * n > size() || other.m * other.n > other.size()) {
|
||||
throw MatrixException(MATRIX_ERR_TOO_FEW_DATA);
|
||||
} else {
|
||||
for (unsigned int i = 0; i < m; i++) {
|
||||
for (unsigned int j = 0; j < other.n; j++) {
|
||||
T temp = v[i * n] * other.v[j];
|
||||
for (unsigned int k = 1; k < n; k++) {
|
||||
temp += v[i * n + k] * other.v[k * other.n + j];
|
||||
}
|
||||
result.v.push_back(temp);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
#endif /* _MATRIX_H */
|
||||
70
Task/Matrix-multiplication/C/matrix-multiplication.c
Normal file
70
Task/Matrix-multiplication/C/matrix-multiplication.c
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
/* Make the data structure self-contained. Element at row i and col j
|
||||
is x[i * w + j]. More often than not, though, you might want
|
||||
to represent a matrix some other way */
|
||||
typedef struct { int h, w; double *x;} matrix_t, *matrix;
|
||||
|
||||
inline double dot(double *a, double *b, int len, int step)
|
||||
{
|
||||
double r = 0;
|
||||
while (len--) {
|
||||
r += *a++ * *b;
|
||||
b += step;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
matrix mat_new(int h, int w)
|
||||
{
|
||||
matrix r = malloc(sizeof(matrix_t) + sizeof(double) * w * h);
|
||||
r->h = h, r->w = w;
|
||||
r->x = (double*)(r + 1);
|
||||
return r;
|
||||
}
|
||||
|
||||
matrix mat_mul(matrix a, matrix b)
|
||||
{
|
||||
matrix r;
|
||||
double *p, *pa;
|
||||
int i, j;
|
||||
if (a->w != b->h) return 0;
|
||||
|
||||
r = mat_new(a->h, b->w);
|
||||
p = r->x;
|
||||
for (pa = a->x, i = 0; i < a->h; i++, pa += a->w)
|
||||
for (j = 0; j < b->w; j++)
|
||||
*p++ = dot(pa, b->x + j, a->w, b->w);
|
||||
return r;
|
||||
}
|
||||
|
||||
void mat_show(matrix a)
|
||||
{
|
||||
int i, j;
|
||||
double *p = a->x;
|
||||
for (i = 0; i < a->h; i++, putchar('\n'))
|
||||
for (j = 0; j < a->w; j++)
|
||||
printf("\t%7.3f", *p++);
|
||||
putchar('\n');
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
double da[] = { 1, 1, 1, 1,
|
||||
2, 4, 8, 16,
|
||||
3, 9, 27, 81,
|
||||
4,16, 64, 256 };
|
||||
double db[] = { 4.0, -3.0, 4.0/3,
|
||||
-13.0/3, 19.0/4, -7.0/3,
|
||||
3.0/2, -2.0, 7.0/6,
|
||||
-1.0/6, 1.0/4, -1.0/6};
|
||||
|
||||
matrix_t a = { 4, 4, da }, b = { 4, 3, db };
|
||||
matrix c = mat_mul(&a, &b);
|
||||
|
||||
/* mat_show(&a), mat_show(&b); */
|
||||
mat_show(c);
|
||||
/* free(c) */
|
||||
return 0;
|
||||
}
|
||||
17
Task/Matrix-multiplication/Clojure/matrix-multiplication.clj
Normal file
17
Task/Matrix-multiplication/Clojure/matrix-multiplication.clj
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
(defn transpose
|
||||
[s]
|
||||
(apply map vector s))
|
||||
|
||||
(defn nested-for
|
||||
[f x y]
|
||||
(map (fn [a]
|
||||
(map (fn [b]
|
||||
(f a b)) y))
|
||||
x))
|
||||
|
||||
(defn matrix-mult
|
||||
[a b]
|
||||
(nested-for (fn [x y] (reduce + (map * x y))) a (transpose b)))
|
||||
|
||||
(def ma [[1 1 1 1] [2 4 8 16] [3 9 27 81] [4 16 64 256]])
|
||||
(def mb [[4 -3 4/3 -1/4] [-13/3 19/4 -7/3 11/24] [3/2 -2 7/6 -1/4] [-1/6 1/4 -1/6 1/24]])
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
(defun matrix-multiply (a b)
|
||||
(flet ((col (mat i) (mapcar #'(lambda (row) (elt row i)) mat))
|
||||
(row (mat i) (elt mat i)))
|
||||
(loop for row from 0 below (length a)
|
||||
collect (loop for col from 0 below (length (row b 0))
|
||||
collect (apply #'+ (mapcar #'* (row a row) (col b col)))))))
|
||||
|
||||
;; example use:
|
||||
(matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
(defun matrix-multiply (matrix1 matrix2)
|
||||
(mapcar
|
||||
(lambda (row)
|
||||
(apply #'mapcar
|
||||
(lambda (&rest column)
|
||||
(apply #'+ (mapcar #'* row column))) matrix2)) matrix1))
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
(defun mmul (A B)
|
||||
(let* ((m (car (array-dimensions A)))
|
||||
(n (cadr (array-dimensions A)))
|
||||
(l (cadr (array-dimensions B)))
|
||||
(C (make-array `(,m ,l) :initial-element 0)))
|
||||
(loop for i from 0 to (- m 1) do
|
||||
(loop for k from 0 to (- l 1) do
|
||||
(setf (aref C i k)
|
||||
(loop for j from 0 to (- n 1)
|
||||
sum (* (aref A i j)
|
||||
(aref B j k))))))
|
||||
C))
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
(mmul #2a((1 2) (3 4)) #2a((-3 -8 3) (-2 1 4)))
|
||||
#2A((-7 -6 11) (-17 -20 25))
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
(defun mmult (a b)
|
||||
(loop
|
||||
with m = (array-dimension a 0)
|
||||
with n = (array-dimension a 1)
|
||||
with l = (array-dimension b 1)
|
||||
with c = (make-array (list m l) :initial-element 0)
|
||||
for i below m do
|
||||
(loop for k below l do
|
||||
(setf (aref c i k)
|
||||
(loop for j below n
|
||||
sum (* (aref a i j)
|
||||
(aref b j k)))))
|
||||
finally (return c)))
|
||||
34
Task/Matrix-multiplication/D/matrix-multiplication.d
Normal file
34
Task/Matrix-multiplication/D/matrix-multiplication.d
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import std.stdio, std.string, std.conv, std.numeric,
|
||||
std.array, std.algorithm;
|
||||
|
||||
bool isRectangular(T)(in T[][] M) /*pure nothrow*/ {
|
||||
return M.all!(row => row.length == M[0].length);
|
||||
}
|
||||
|
||||
T[][] matrixMul(T)(in T[][] A, in T[][] B) /*pure nothrow*/
|
||||
in {
|
||||
assert(A.isRectangular && B.isRectangular &&
|
||||
!A.empty && !B.empty && A[0].length == B.length);
|
||||
} body {
|
||||
auto result = new T[][](A.length, B[0].length);
|
||||
auto aux = new T[B.length];
|
||||
|
||||
foreach (immutable j; 0 .. B[0].length) {
|
||||
foreach (immutable k, const row; B)
|
||||
aux[k] = row[j];
|
||||
foreach (immutable i, const ai; A)
|
||||
result[i][j] = dotProduct(ai, aux);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void main() {
|
||||
immutable a = [[1, 2], [3, 4], [3, 6]];
|
||||
immutable b = [[-3, -8, 3,], [-2, 1, 4]];
|
||||
|
||||
immutable form = "[%([%(%d, %)],\n %)]]";
|
||||
writefln("A = \n" ~ form ~ "\n", a);
|
||||
writefln("B = \n" ~ form ~ "\n", b);
|
||||
writefln("A * B = \n" ~ form, matrixMul(a, b));
|
||||
}
|
||||
34
Task/Matrix-multiplication/EGL/matrix-multiplication.egl
Normal file
34
Task/Matrix-multiplication/EGL/matrix-multiplication.egl
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
program Matrix_multiplication type BasicProgram {}
|
||||
|
||||
function main()
|
||||
a float[][] = [[1,2,3],[4,5,6]];
|
||||
b float[][] = [[1,2],[3,4],[5,6]];
|
||||
c float[][] = mult(a, b);
|
||||
end
|
||||
|
||||
function mult(a float[][], b float[][]) returns(float[][])
|
||||
if(a.getSize() == 0)
|
||||
return (new float[0][0]);
|
||||
end
|
||||
if(a[1].getSize() != b.getSize())
|
||||
return (null); //invalid dims
|
||||
end
|
||||
|
||||
n int = a[1].getSize();
|
||||
m int = a.getSize();
|
||||
p int = b[1].getSize();
|
||||
|
||||
ans float[0][0];
|
||||
ans.resizeAll([m, p]);
|
||||
|
||||
// Calculate dot product.
|
||||
for(i int from 1 to m)
|
||||
for(j int from 1 to p)
|
||||
for(k int from 1 to n)
|
||||
ans[i][j] += a[i][k] * b[k][j];
|
||||
end
|
||||
end
|
||||
end
|
||||
return (ans);
|
||||
end
|
||||
end
|
||||
45
Task/Matrix-multiplication/ELLA/matrix-multiplication.ella
Normal file
45
Task/Matrix-multiplication/ELLA/matrix-multiplication.ella
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
MAC ZIP = ([INT n]TYPE t: vector1 vector2) -> [n][2]t:
|
||||
[INT k = 1..n](vector1[k], vector2[k]).
|
||||
|
||||
MAC TRANSPOSE = ([INT n][INT m]TYPE t: matrix) -> [m][n]t:
|
||||
[INT i = 1..m] [INT j = 1..n] matrix[j][i].
|
||||
|
||||
MAC INNER_PRODUCT{FN * = [2]TYPE t -> TYPE s, FN + = [2]s -> s}
|
||||
= ([INT n][2]t: vector) -> s:
|
||||
IF n = 1 THEN *vector[1]
|
||||
ELSE *vector[1] + INNER_PRODUCT {*,+} vector[2..n]
|
||||
FI.
|
||||
|
||||
MAC MATRIX_MULT {FN * = [2]TYPE t->TYPE s, FN + = [2]s->s} =
|
||||
([INT n][INT m]t: matrix1, [m][INT p]t: matrix2) -> [n][p]s:
|
||||
BEGIN
|
||||
LET transposed_matrix2 = TRANSPOSE matrix2.
|
||||
OUTPUT [INT i = 1..n][INT j = 1..p]
|
||||
INNER_PRODUCT{*,+}ZIP(matrix1[i],transposed_matrix2[j])
|
||||
END.
|
||||
|
||||
|
||||
TYPE element = NEW elt/(1..20),
|
||||
product = NEW prd/(1..1200).
|
||||
|
||||
FN PLUS = (product: integer1 integer2) -> product:
|
||||
ARITH integer1 + integer2.
|
||||
|
||||
FN MULT = (element: integer1 integer2) -> product:
|
||||
ARITH integer1 * integer2.
|
||||
|
||||
FN MULT_234 = ([2][3]element:matrix1, [3][4]element:matrix2) ->
|
||||
[2][4]product:
|
||||
MATRIX_MULT{MULT,PLUS}(matrix1, matrix2).
|
||||
|
||||
FN TEST = () -> [2][4]product:
|
||||
( LET m1 = ((elt/2, elt/1, elt/1),
|
||||
(elt/3, elt/6, elt/9)),
|
||||
m2 = ((elt/6, elt/1, elt/3, elt/4),
|
||||
(elt/9, elt/2, elt/8, elt/3),
|
||||
(elt/6, elt/4, elt/1, elt/2)).
|
||||
OUTPUT
|
||||
MULT_234 (m1, m2)
|
||||
).
|
||||
|
||||
COM test: just displaysignal MOC
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
function matrix_mul(sequence a, sequence b)
|
||||
sequence c
|
||||
if length(a[1]) != length(b) then
|
||||
return 0
|
||||
else
|
||||
c = repeat(repeat(0,length(b[1])),length(a))
|
||||
for i = 1 to length(a) do
|
||||
for j = 1 to length(b[1]) do
|
||||
for k = 1 to length(a[1]) do
|
||||
c[i][j] += a[i][k]*b[k][j]
|
||||
end for
|
||||
end for
|
||||
end for
|
||||
return c
|
||||
end if
|
||||
end function
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
class Main
|
||||
{
|
||||
// multiply two matrices (with no error checking)
|
||||
public static Int[][] multiply (Int[][] m1, Int[][] m2)
|
||||
{
|
||||
Int[][] result := [,]
|
||||
m1.each |Int[] row1|
|
||||
{
|
||||
Int[] row := [,]
|
||||
m2[0].size.times |Int colNumber|
|
||||
{
|
||||
Int value := 0
|
||||
m2.each |Int[] row2, Int index|
|
||||
{
|
||||
value += row1[index] * row2[colNumber]
|
||||
}
|
||||
row.add (value)
|
||||
}
|
||||
result.add (row)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
public static Void main ()
|
||||
{
|
||||
m1 := [[1,2,3],[4,5,6]]
|
||||
m2 := [[1,2],[3,4],[5,6]]
|
||||
|
||||
echo ("${m1} times ${m2} = ${multiply(m1,m2)}")
|
||||
}
|
||||
}
|
||||
10
Task/Matrix-multiplication/Forth/matrix-multiplication.fth
Normal file
10
Task/Matrix-multiplication/Forth/matrix-multiplication.fth
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
include fsl-util.f
|
||||
|
||||
3 3 float matrix A{{
|
||||
A{{ 3 3 }}fread 1e 2e 3e 4e 5e 6e 7e 8e 9e
|
||||
3 3 float matrix B{{
|
||||
B{{ 3 3 }}fread 3e 3e 3e 2e 2e 2e 1e 1e 1e
|
||||
3 3 float matrix C{{ \ result
|
||||
|
||||
A{{ B{{ C{{ mat*
|
||||
C{{ }}print
|
||||
25
Task/Matrix-multiplication/Fortran/matrix-multiplication.f
Normal file
25
Task/Matrix-multiplication/Fortran/matrix-multiplication.f
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
real, dimension(n,m) :: a = reshape( (/ (i, i=1, n*m) /), (/ n, m /) )
|
||||
real, dimension(m,k) :: b = reshape( (/ (i, i=1, m*k) /), (/ m, k /) )
|
||||
real, dimension(size(a,1), size(b,2)) :: c ! C is an array whose first dimension (row) size
|
||||
! is the same as A's first dimension size, and
|
||||
! whose second dimension (column) size is the same
|
||||
! as B's second dimension size.
|
||||
|
||||
c = matmul( a, b )
|
||||
|
||||
print *, 'A'
|
||||
do i = 1, n
|
||||
print *, a(i,:)
|
||||
end do
|
||||
|
||||
print *,
|
||||
print *, 'B'
|
||||
do i = 1, m
|
||||
print *, b(i,:)
|
||||
end do
|
||||
|
||||
print *,
|
||||
print *, 'C = AB'
|
||||
do i = 1, n
|
||||
print *, c(i,:)
|
||||
end do
|
||||
20
Task/Matrix-multiplication/Frink/matrix-multiplication.frink
Normal file
20
Task/Matrix-multiplication/Frink/matrix-multiplication.frink
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
matprod[a is array, b is array] :=
|
||||
{
|
||||
c = makeArray[[length[a], length[b@0]], 0]
|
||||
|
||||
a_row = length[a]-1
|
||||
a_col = length[a@0]-1
|
||||
b_col = length[b]-1
|
||||
|
||||
for row = 0 to a_row
|
||||
{
|
||||
for col = 0 to b_col
|
||||
{
|
||||
for inc = 0 to a_col
|
||||
{
|
||||
c@row@col = c@row@col + (a@row@inc * b@inc@col)
|
||||
}
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
19
Task/Matrix-multiplication/GAP/matrix-multiplication.gap
Normal file
19
Task/Matrix-multiplication/GAP/matrix-multiplication.gap
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
# Built-in
|
||||
A := [[1, 2], [3, 4], [5, 6], [7, 8]];
|
||||
B := [[1, 2, 3], [4, 5, 6]];
|
||||
|
||||
PrintArray(A);
|
||||
# [ [ 1, 2 ],
|
||||
# [ 3, 4 ],
|
||||
# [ 5, 6 ],
|
||||
# [ 7, 8 ] ]
|
||||
|
||||
PrintArray(B);
|
||||
# [ [ 1, 2, 3 ],
|
||||
# [ 4, 5, 6 ] ]
|
||||
|
||||
PrintArray(A * B);
|
||||
# [ [ 9, 12, 15 ],
|
||||
# [ 19, 26, 33 ],
|
||||
# [ 29, 40, 51 ],
|
||||
# [ 39, 54, 69 ] ]
|
||||
54
Task/Matrix-multiplication/Go/matrix-multiplication-1.go
Normal file
54
Task/Matrix-multiplication/Go/matrix-multiplication-1.go
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type Value float64
|
||||
type Matrix [][]Value
|
||||
|
||||
func Multiply(m1, m2 Matrix) (m3 Matrix, ok bool) {
|
||||
rows, cols, extra := len(m1), len(m2[0]), len(m2)
|
||||
if len(m1[0]) != extra { return nil, false }
|
||||
m3 = make(Matrix, rows)
|
||||
for i := 0; i < rows; i++ {
|
||||
m3[i] = make([]Value,cols)
|
||||
for j := 0; j < cols; j++ {
|
||||
for k := 0; k < extra; k++ {
|
||||
m3[i][j] += m1[i][k] * m2[k][j]
|
||||
}
|
||||
}
|
||||
}
|
||||
return m3, true
|
||||
}
|
||||
|
||||
func (m Matrix) String() string {
|
||||
rows := len(m)
|
||||
cols := len(m[0])
|
||||
out := "["
|
||||
for r := 0; r < rows; r++ {
|
||||
if r > 0 { out += ",\n " }
|
||||
out += "[ "
|
||||
for c := 0; c < cols; c++ {
|
||||
if c > 0 { out += ", " }
|
||||
out += fmt.Sprintf("%7.3f", m[r][c])
|
||||
}
|
||||
out += " ]"
|
||||
}
|
||||
out += "]"
|
||||
return out
|
||||
}
|
||||
|
||||
func main() {
|
||||
A := Matrix{[]Value{1, 1, 1, 1},
|
||||
[]Value{2, 4, 8, 16},
|
||||
[]Value{3, 9, 27, 81},
|
||||
[]Value{4, 16, 64, 256}}
|
||||
B := Matrix{[]Value{ 4.0 , -3.0 , 4.0/3, -1.0/4 },
|
||||
[]Value{-13.0/3, 19.0/4, -7.0/3, 11.0/24},
|
||||
[]Value{ 3.0/2, -2.0 , 7.0/6, -1.0/4 },
|
||||
[]Value{ -1.0/6, 1.0/4, -1.0/6, 1.0/24}}
|
||||
P,ok := Multiply(A,B)
|
||||
if !ok { panic("Invalid dimensions") }
|
||||
fmt.Printf("Matrix A:\n%s\n\n", A)
|
||||
fmt.Printf("Matrix B:\n%s\n\n", B)
|
||||
fmt.Printf("Product of A and B:\n%s\n\n", P)
|
||||
}
|
||||
89
Task/Matrix-multiplication/Go/matrix-multiplication-2.go
Normal file
89
Task/Matrix-multiplication/Go/matrix-multiplication-2.go
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type matrix struct {
|
||||
ele []float64
|
||||
stride int
|
||||
}
|
||||
|
||||
func matrixFromRows(rows [][]float64) *matrix {
|
||||
if len(rows) == 0 {
|
||||
return &matrix{nil, 0}
|
||||
}
|
||||
m := &matrix{make([]float64, len(rows)*len(rows[0])), len(rows[0])}
|
||||
for rx, row := range rows {
|
||||
copy(m.ele[rx*m.stride:(rx+1)*m.stride], row)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *matrix) print(heading string) {
|
||||
if heading > "" {
|
||||
fmt.Print("\n", heading, "\n")
|
||||
}
|
||||
for e := 0; e < len(m.ele); e += m.stride {
|
||||
fmt.Printf("%6.3f ", m.ele[e:e+m.stride])
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
func (m1 *matrix) multiply(m2 *matrix) (m3 *matrix, ok bool) {
|
||||
if m1.stride*m2.stride != len(m2.ele) {
|
||||
return nil, false
|
||||
}
|
||||
m3 = &matrix{make([]float64, (len(m1.ele)/m1.stride)*m2.stride), m2.stride}
|
||||
for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.stride {
|
||||
for m2r0 := 0; m2r0 < m2.stride; m2r0++ {
|
||||
for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.stride {
|
||||
m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]
|
||||
m1x++
|
||||
}
|
||||
m3x++
|
||||
}
|
||||
}
|
||||
return m3, true
|
||||
}
|
||||
|
||||
func main() {
|
||||
a := matrixFromRows([][]float64{
|
||||
{1, 1, 1, 1},
|
||||
{2, 4, 8, 16},
|
||||
{3, 9, 27, 81},
|
||||
{4, 16, 64, 256},
|
||||
})
|
||||
b := matrixFromRows([][]float64{
|
||||
{
|
||||
4,
|
||||
-3,
|
||||
4. / 3,
|
||||
-1. / 4,
|
||||
},
|
||||
{
|
||||
-13. / 3,
|
||||
19. / 4,
|
||||
-7. / 3,
|
||||
11. / 24,
|
||||
},
|
||||
{
|
||||
3. / 2,
|
||||
-2,
|
||||
7. / 6,
|
||||
-1. / 4,
|
||||
},
|
||||
{
|
||||
-1. / 6,
|
||||
1. / 4,
|
||||
-1. / 6,
|
||||
1. / 24,
|
||||
},
|
||||
})
|
||||
p, ok := a.multiply(b)
|
||||
a.print("Matrix A:")
|
||||
b.print("Matrix B:")
|
||||
if !ok {
|
||||
fmt.Println("not conformable for matrix multiplication")
|
||||
return
|
||||
}
|
||||
p.print("Product of A and B:")
|
||||
}
|
||||
50
Task/Matrix-multiplication/Go/matrix-multiplication-3.go
Normal file
50
Task/Matrix-multiplication/Go/matrix-multiplication-3.go
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
mat "github.com/skelterjohn/go.matrix"
|
||||
)
|
||||
|
||||
func main() {
|
||||
a := mat.MakeDenseMatrixStacked([][]float64{
|
||||
{1, 1, 1, 1},
|
||||
{2, 4, 8, 16},
|
||||
{3, 9, 27, 81},
|
||||
{4, 16, 64, 256},
|
||||
})
|
||||
b := mat.MakeDenseMatrixStacked([][]float64{
|
||||
{
|
||||
4,
|
||||
-3,
|
||||
4. / 3,
|
||||
-1. / 4,
|
||||
},
|
||||
{
|
||||
-13. / 3,
|
||||
19. / 4,
|
||||
-7. / 3,
|
||||
11. / 24,
|
||||
},
|
||||
{
|
||||
3. / 2,
|
||||
-2,
|
||||
7. / 6,
|
||||
-1. / 4,
|
||||
},
|
||||
{
|
||||
-1. / 6,
|
||||
1. / 4,
|
||||
-1. / 6,
|
||||
1. / 24,
|
||||
},
|
||||
})
|
||||
p, err := a.TimesDense(b)
|
||||
fmt.Printf("Matrix A:\n%v\n", a)
|
||||
fmt.Printf("Matrix B:\n%v\n", b)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Printf("Product of A and B:\n%v\n", p)
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
def assertConformable = { a, b ->
|
||||
assert a instanceof List
|
||||
assert b instanceof List
|
||||
assert a.every { it instanceof List && it.size() == b.size() }
|
||||
assert b.every { it instanceof List && it.size() == b[0].size() }
|
||||
}
|
||||
|
||||
def matmulWOIL = { a, b ->
|
||||
assertConformable(a, b)
|
||||
|
||||
def bt = b.transpose()
|
||||
a.collect { ai ->
|
||||
bt.collect { btj ->
|
||||
[ai, btj].transpose().collect { it[0] * it[1] }.sum()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
def matmulWOT = { a, b ->
|
||||
assertConformable(a, b)
|
||||
|
||||
(0..<a.size()).collect { i ->
|
||||
(0..<b[0].size()).collect { j ->
|
||||
(0..<b.size()).collect { k -> a[i][k] * b[k][j] }.sum()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
def m4by2 = [ [ 1, 2 ],
|
||||
[ 3, 4 ],
|
||||
[ 5, 6 ],
|
||||
[ 7, 8 ] ]
|
||||
|
||||
def m2by3 = [ [ 1, 2, 3 ],
|
||||
[ 4, 5, 6 ] ]
|
||||
|
||||
matmulWOIL(m4by2, m2by3).each { println it }
|
||||
println()
|
||||
matmulWOT(m4by2, m2by3).each { println it }
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
import Data.List
|
||||
|
||||
mmult :: Num a => [[a]] -> [[a]] -> [[a]]
|
||||
mmult a b = [ [ sum $ zipWith (*) ar bc | bc <- (transpose b) ] | ar <- a ]
|
||||
|
||||
-- Example use:
|
||||
test = [[1, 2],
|
||||
[3, 4]] `mmult` [[-3, -8, 3],
|
||||
[-2, 1, 4]]
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import Data.Array
|
||||
|
||||
mmult :: (Ix i, Num a) => Array (i,i) a -> Array (i,i) a -> Array (i,i) a
|
||||
mmult x y
|
||||
| x1 /= y0 || x1' /= y0' = error "range mismatch"
|
||||
| otherwise = array ((x0,y1),(x0',y1')) l
|
||||
where
|
||||
((x0,x1),(x0',x1')) = bounds x
|
||||
((y0,y1),(y0',y1')) = bounds y
|
||||
ir = range (x0,x0')
|
||||
jr = range (y1,y1')
|
||||
kr = range (x1,x1')
|
||||
l = [((i,j), sum [x!(i,k) * y!(k,j) | k <- kr]) | i <- ir, j <- jr]
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
REAL :: m=4, n=2, p=3, a(m,n), b(n,p), res(m,p)
|
||||
|
||||
a = $ ! initialize to 1, 2, ..., m*n
|
||||
b = $ ! initialize to 1, 2, ..., n*p
|
||||
|
||||
res = 0
|
||||
DO i = 1, m
|
||||
DO j = 1, p
|
||||
DO k = 1, n
|
||||
res(i,j) = res(i,j) + a(i,k) * b(k,j)
|
||||
ENDDO
|
||||
ENDDO
|
||||
ENDDO
|
||||
|
||||
DLG(DefWidth=4, Text=a, Text=b,Y=0, Text=res,Y=0)
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
a b res
|
||||
1 2 1 2 3 9 12 15
|
||||
3 4 4 5 6 19 26 33
|
||||
5 6 29 40 51
|
||||
7 8 39 54 69
|
||||
1
Task/Matrix-multiplication/IDL/matrix-multiplication.idl
Normal file
1
Task/Matrix-multiplication/IDL/matrix-multiplication.idl
Normal file
|
|
@ -0,0 +1 @@
|
|||
result = arr1 # arr2
|
||||
13
Task/Matrix-multiplication/Icon/matrix-multiplication-1.icon
Normal file
13
Task/Matrix-multiplication/Icon/matrix-multiplication-1.icon
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
link matrix
|
||||
|
||||
procedure main ()
|
||||
m1 := [[1,2,3], [4,5,6]]
|
||||
m2 := [[1,2],[3,4],[5,6]]
|
||||
m3 := mult_matrix (m1, m2)
|
||||
write ("Multiply:")
|
||||
write_matrix ("", m1) # first argument is filename, or "" for stdout
|
||||
write ("by:")
|
||||
write_matrix ("", m2)
|
||||
write ("Result: ")
|
||||
write_matrix ("", m3)
|
||||
end
|
||||
15
Task/Matrix-multiplication/Icon/matrix-multiplication-2.icon
Normal file
15
Task/Matrix-multiplication/Icon/matrix-multiplication-2.icon
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
procedure multiply_matrix (m1, m2)
|
||||
result := [] # to hold the final matrix
|
||||
every row1 := !m1 do { # loop through each row in the first matrix
|
||||
row := []
|
||||
every colIndex := 1 to *m1 do { # and each column index of the result
|
||||
value := 0
|
||||
every rowIndex := 1 to *m2 do {
|
||||
value +:= row1[rowIndex] * m2[rowIndex][colIndex]
|
||||
}
|
||||
put (row, value)
|
||||
}
|
||||
put (result, row) # add each row as it is complete
|
||||
}
|
||||
return result
|
||||
end
|
||||
10
Task/Matrix-multiplication/J/matrix-multiplication-1.j
Normal file
10
Task/Matrix-multiplication/J/matrix-multiplication-1.j
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
mp =: +/ .* NB. Matrix product
|
||||
|
||||
A =: ^/~>:i. 4 NB. Same A as in other examples (1 1 1 1, 2 4 8 16, 3 9 27 81,:4 16 64 256)
|
||||
B =: %.A NB. Matrix inverse of A
|
||||
|
||||
'6.2' 8!:2 A mp B
|
||||
1.00 0.00 0.00 0.00
|
||||
0.00 1.00 0.00 0.00
|
||||
0.00 0.00 1.00 0.00
|
||||
0.00 0.00 0.00 1.00
|
||||
3
Task/Matrix-multiplication/J/matrix-multiplication-2.j
Normal file
3
Task/Matrix-multiplication/J/matrix-multiplication-2.j
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
x ~:/ .*. y NB. boolean inner product ( ~: is "not equal" (exclusive or) and *. is "and")
|
||||
x *./ .= y NB. which rows of x are the same as vector y?
|
||||
x + / .= y NB. number of places where a value in row x equals the corresponding value in y
|
||||
19
Task/Matrix-multiplication/Java/matrix-multiplication.java
Normal file
19
Task/Matrix-multiplication/Java/matrix-multiplication.java
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
public static double[][] mult(double a[][], double b[][]){//a[m][n], b[n][p]
|
||||
if(a.length == 0) return new double[0][0];
|
||||
if(a[0].length != b.length) return null; //invalid dims
|
||||
|
||||
int n = a[0].length;
|
||||
int m = a.length;
|
||||
int p = b[0].length;
|
||||
|
||||
double ans[][] = new double[m][p];
|
||||
|
||||
for(int i = 0;i < m;i++){
|
||||
for(int j = 0;j < p;j++){
|
||||
for(int k = 0;k < n;k++){
|
||||
ans[i][j] += a[i][k] * b[k][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
// returns a new matrix
|
||||
Matrix.prototype.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));
|
||||
3
Task/Matrix-multiplication/K/matrix-multiplication.k
Normal file
3
Task/Matrix-multiplication/K/matrix-multiplication.k
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(1 2;3 4)_mul (5 6;7 8)
|
||||
(19 22
|
||||
43 50)
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
[[1 2 3] [4 5 6]] 'm dress
|
||||
[[1 2] [3 4] [5 6]] 'm dress * .
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
MatrixA$ ="4, 4, 1, 1, 1, 1, 2, 4, 8, 16, 3, 9, 27, 81, 4, 16, 64, 256"
|
||||
MatrixB$ ="4, 4, 4, -3, 4/3, -1/4 , -13/3, 19/4, -7/3, 11/24, 3/2, -2, 7/6, -1/4, -1/6, 1/4, -1/6, 1/24"
|
||||
|
||||
print "Product of two matrices"
|
||||
call DisplayMatrix MatrixA$
|
||||
print " *"
|
||||
call DisplayMatrix MatrixB$
|
||||
print " ="
|
||||
MatrixP$ =MatrixMultiply$( MatrixA$, MatrixB$)
|
||||
call DisplayMatrix MatrixP$
|
||||
105
Task/Matrix-multiplication/Logo/matrix-multiplication.logo
Normal file
105
Task/Matrix-multiplication/Logo/matrix-multiplication.logo
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
TO LISTVMD :A :F :C :NV
|
||||
;PROCEDURE LISTVMD
|
||||
;A = LIST
|
||||
;F = ROWS
|
||||
;C = COLS
|
||||
;NV = NAME OF MATRIX / VECTOR NEW
|
||||
;this procedure transform a list in matrix / vector square or rect
|
||||
|
||||
(LOCAL "CF "CC "NV "T "W)
|
||||
MAKE "CF 1
|
||||
MAKE "CC 1
|
||||
MAKE "NV (MDARRAY (LIST :F :C) 1)
|
||||
MAKE "T :F * :C
|
||||
FOR [Z 1 :T][MAKE "W ITEM :Z :A
|
||||
MDSETITEM (LIST :CF :CC) :NV :W
|
||||
MAKE "CC :CC + 1
|
||||
IF :CC = :C + 1 [MAKE "CF :CF + 1 MAKE "CC 1]]
|
||||
OUTPUT :NV
|
||||
END
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
|
||||
|
||||
TO XX
|
||||
; MAIN PROGRAM
|
||||
;LRCVS 10.04.12
|
||||
; THIS PROGRAM multiplies two "square" matrices / vector ONLY!!!
|
||||
; THE RECTANGULAR NOT WORK!!!
|
||||
|
||||
CT CS HT
|
||||
|
||||
; FIRST DATA MATRIX / VECTOR
|
||||
MAKE "A [1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49]
|
||||
MAKE "FA 5 ;"ROWS
|
||||
MAKE "CA 5 ;"COLS
|
||||
|
||||
; SECOND DATA MATRIX / VECTOR
|
||||
MAKE "B [2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50]
|
||||
MAKE "FB 5 ;"ROWS
|
||||
MAKE "CB 5 ;"COLS
|
||||
|
||||
|
||||
IF (OR :FA <> :CA :FB <>:CB) [PRINT "Las_matrices/vector_no_son_cuadradas THROW
|
||||
"TOPLEVEL ]
|
||||
IFELSE (OR :CA <> :FB :FA <> :CB) [PRINT
|
||||
"Las_matrices/vector_no_son_compatibles THROW "TOPLEVEL ][MAKE "MA LISTVMD :A
|
||||
:FA :CA "MA MAKE "MB LISTVMD :B :FB :CB "MB] ;APPLICATION <<< "LISTVMD"
|
||||
|
||||
PRINT (LIST "THIS_IS: "ROWS "X "COLS)
|
||||
PRINT []
|
||||
PRINT (LIST :MA "=_M1 :FA "ROWS "X :CA "COLS)
|
||||
PRINT []
|
||||
PRINT (LIST :MB "=_M2 :FA "ROWS "X :CA "COLS)
|
||||
PRINT []
|
||||
|
||||
|
||||
MAKE "T :FA * :CB
|
||||
MAKE "RE (ARRAY :T 1)
|
||||
|
||||
|
||||
MAKE "CO 0
|
||||
FOR [AF 1 :CA][
|
||||
FOR [AC 1 :CA][
|
||||
MAKE "TEMP 0
|
||||
FOR [I 1 :CA ][
|
||||
MAKE "TEMP :TEMP + (MDITEM (LIST :I :AF) :MA) * (MDITEM (LIST :AC :I) :MB)]
|
||||
MAKE "CO :CO + 1
|
||||
SETITEM :CO :RE :TEMP]]
|
||||
|
||||
|
||||
PRINT []
|
||||
PRINT (LIST "THIS_IS: :FA "ROWS "X :CB "COLS)
|
||||
SHOW LISTVMD :RE :FA :CB "TO ;APPLICATION <<< "LISTVMD"
|
||||
END
|
||||
|
||||
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\
|
||||
|
||||
|
||||
M1 * M2 RESULT / SOLUTION
|
||||
|
||||
1 3 5 7 9 2 4 6 8 10 830 1880 2930 3980 5030
|
||||
11 13 15 17 19 12 14 16 18 20 890 2040 3190 4340 5490
|
||||
21 23 25 27 29 X 22 24 26 28 30 = 950 2200 3450 4700 5950
|
||||
31 33 35 37 39 32 34 36 38 40 1010 2360 3710 5060 6410
|
||||
41 43 45 47 49 42 44 46 48 50 1070 2520 3970 5420 6870
|
||||
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\
|
||||
|
||||
|
||||
NOW IN LOGO!!!!
|
||||
|
||||
|
||||
THIS_IS: ROWS X COLS
|
||||
|
||||
{{1 3 5 7 9} {11 13 15 17 19} {21 23 25 27 29} {31 33 35 37 39} {41 43 45 47
|
||||
49}} =_M1 5 ROWS X 5 COLS
|
||||
|
||||
{{2 4 6 8 10} {12 14 16 18 20} {22 24 26 28 30} {32 34 36 38 40} {42 44 46 48
|
||||
50}} =_M2 5 ROWS X 5 COLS
|
||||
|
||||
|
||||
THIS_IS: 5 ROWS X 5 COLS
|
||||
{{830 1880 2930 3980 5030} {890 2040 3190 4340 5490} {950 2200 3450 4700 5950}
|
||||
{1010 2360 3710 5060 6410} {1070 2520 3970 5420 6870}}
|
||||
31
Task/Matrix-multiplication/Lua/matrix-multiplication.lua
Normal file
31
Task/Matrix-multiplication/Lua/matrix-multiplication.lua
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
function MatMul( m1, m2 )
|
||||
if #m1[1] ~= #m2 then -- inner matrix-dimensions must agree
|
||||
return nil
|
||||
end
|
||||
|
||||
local res = {}
|
||||
|
||||
for i = 1, #m1 do
|
||||
res[i] = {}
|
||||
for j = 1, #m2[1] do
|
||||
res[i][j] = 0
|
||||
for k = 1, #m2 do
|
||||
res[i][j] = res[i][j] + m1[i][k] * m2[k][j]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return res
|
||||
end
|
||||
|
||||
-- Test for MatMul
|
||||
mat1 = { { 1, 2, 3 }, { 4, 5, 6 } }
|
||||
mat2 = { { 1, 2 }, { 3, 4 }, { 5, 6 } }
|
||||
erg = MatMul( mat1, mat2 )
|
||||
for i = 1, #erg do
|
||||
for j = 1, #erg[1] do
|
||||
io.write( erg[i][j] )
|
||||
io.write(" ")
|
||||
end
|
||||
io.write("\n")
|
||||
end
|
||||
27
Task/Matrix-multiplication/MATLAB/matrix-multiplication.m
Normal file
27
Task/Matrix-multiplication/MATLAB/matrix-multiplication.m
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
>> A = [1 2;3 4]
|
||||
|
||||
A =
|
||||
|
||||
1 2
|
||||
3 4
|
||||
|
||||
>> B = [5 6;7 8]
|
||||
|
||||
B =
|
||||
|
||||
5 6
|
||||
7 8
|
||||
|
||||
>> A * B
|
||||
|
||||
ans =
|
||||
|
||||
19 22
|
||||
43 50
|
||||
|
||||
>> mtimes(A,B)
|
||||
|
||||
ans =
|
||||
|
||||
19 22
|
||||
43 50
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
M1 = {{1, 2},
|
||||
{3, 4},
|
||||
{5, 6},
|
||||
{7, 8}}
|
||||
M2 = {{1, 2, 3},
|
||||
{4, 5, 6}}
|
||||
M = M1.M2
|
||||
|
|
@ -0,0 +1 @@
|
|||
{{1, 2}, {3, 4}, {5, 6}, {7, 8}}.{{1, 2, 3}, {4, 5, 6}}
|
||||
|
|
@ -0,0 +1 @@
|
|||
{{9, 12, 15}, {19, 26, 33}, {29, 40, 51}, {39, 54, 69}}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
a: matrix([1, 2],
|
||||
[3, 4],
|
||||
[5, 6],
|
||||
[7, 8])$
|
||||
|
||||
b: matrix([1, 2, 3],
|
||||
[4, 5, 6])$
|
||||
|
||||
a . b;
|
||||
/* matrix([ 9, 12, 15],
|
||||
[19, 26, 33],
|
||||
[29, 40, 51],
|
||||
[39, 54, 69]) */
|
||||
18
Task/Matrix-multiplication/Perl/matrix-multiplication.pl
Normal file
18
Task/Matrix-multiplication/Perl/matrix-multiplication.pl
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
sub mmult
|
||||
{
|
||||
our @a; local *a = shift;
|
||||
our @b; local *b = shift;
|
||||
my @p = [];
|
||||
my $rows = @a;
|
||||
my $cols = @{ $b[0] };
|
||||
my $n = @b - 1;
|
||||
for (my $r = 0 ; $r < $rows ; ++$r)
|
||||
{
|
||||
for (my $c = 0 ; $c < $cols ; ++$c)
|
||||
{
|
||||
$p[$r][$c] += $a[$r][$_] * $b[$_][$c]
|
||||
foreach 0 .. $n;
|
||||
}
|
||||
}
|
||||
return [@p];
|
||||
}
|
||||
10
Task/Matrix-multiplication/PicoLisp/matrix-multiplication.l
Normal file
10
Task/Matrix-multiplication/PicoLisp/matrix-multiplication.l
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
(de matMul (Mat1 Mat2)
|
||||
(mapcar
|
||||
'((Row)
|
||||
(apply mapcar Mat2
|
||||
'(@ (sum * Row (rest))) ) )
|
||||
Mat1 ) )
|
||||
|
||||
(matMul
|
||||
'((1 2 3) (4 5 6))
|
||||
'((6 -1) (3 2) (0 -3)) )
|
||||
11
Task/Matrix-multiplication/Prolog/matrix-multiplication.pro
Normal file
11
Task/Matrix-multiplication/Prolog/matrix-multiplication.pro
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
% SWI-Prolog has transpose/2 in its clpfd library
|
||||
:- use_module(library(clpfd)).
|
||||
|
||||
% N is the dot product of lists V1 and V2.
|
||||
dot(V1, V2, N) :- maplist(product,V1,V2,P), sumlist(P,N).
|
||||
product(N1,N2,N3) :- N3 is N1*N2.
|
||||
|
||||
% Matrix multiplication with matrices represented
|
||||
% as lists of lists. M3 is the product of M1 and M2
|
||||
mmult(M1, M2, M3) :- transpose(M2,MT), maplist(mm_helper(MT), M1, M3).
|
||||
mm_helper(M2, I1, M3) :- maplist(dot(I1), M2, M3).
|
||||
38
Task/Matrix-multiplication/Python/matrix-multiplication-1.py
Normal file
38
Task/Matrix-multiplication/Python/matrix-multiplication-1.py
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
a=((1, 1, 1, 1), # matrix A #
|
||||
(2, 4, 8, 16),
|
||||
(3, 9, 27, 81),
|
||||
(4, 16, 64, 256))
|
||||
|
||||
b=(( 4 , -3 , 4/3., -1/4. ), # matrix B #
|
||||
(-13/3., 19/4., -7/3., 11/24.),
|
||||
( 3/2., -2. , 7/6., -1/4. ),
|
||||
( -1/6., 1/4., -1/6., 1/24.))
|
||||
|
||||
|
||||
|
||||
def MatrixMul( mtx_a, mtx_b):
|
||||
tpos_b = zip( *mtx_b)
|
||||
rtn = [[ sum( ea*eb for ea,eb in zip(a,b)) for b in tpos_b] for a in mtx_a]
|
||||
return rtn
|
||||
|
||||
|
||||
v = MatrixMul( a, b )
|
||||
|
||||
print 'v = ('
|
||||
for r in v:
|
||||
print '[',
|
||||
for val in r:
|
||||
print '%8.2f '%val,
|
||||
print ']'
|
||||
print ')'
|
||||
|
||||
|
||||
u = MatrixMul(b,a)
|
||||
|
||||
print 'u = '
|
||||
for r in u:
|
||||
print '[',
|
||||
for val in r:
|
||||
print '%8.2f '%val,
|
||||
print ']'
|
||||
print ')'
|
||||
10
Task/Matrix-multiplication/Python/matrix-multiplication-2.py
Normal file
10
Task/Matrix-multiplication/Python/matrix-multiplication-2.py
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
from operator import mul
|
||||
|
||||
def matrixMul(m1, m2):
|
||||
return map(
|
||||
lambda row:
|
||||
map(
|
||||
lambda *column:
|
||||
sum(map(mul, row, column)),
|
||||
*m2),
|
||||
m1)
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
def mm(A, B):
|
||||
return [[sum(x * B[i][col] for i,x in enumerate(row)) for col in range(len(B[0]))] for row in A]
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import numpy as np
|
||||
np.dot(a,b)
|
||||
#or if a is an array
|
||||
a.dot(b)
|
||||
1
Task/Matrix-multiplication/R/matrix-multiplication.r
Normal file
1
Task/Matrix-multiplication/R/matrix-multiplication.r
Normal file
|
|
@ -0,0 +1 @@
|
|||
a %*% b
|
||||
37
Task/Matrix-multiplication/REXX/matrix-multiplication.rexx
Normal file
37
Task/Matrix-multiplication/REXX/matrix-multiplication.rexx
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
/*REXX program multiplies two matrixes together, shows matrixes & result*/
|
||||
x.=
|
||||
x.1 = '1 2'
|
||||
x.2 = '3 4'
|
||||
x.3 = "5 6" /*either kind of quote works. */
|
||||
x.4 = '7 8'
|
||||
do r=1 while x.r\=='' /*build the "A" matric from X. #s*/
|
||||
do c=1 while x.r\==''; parse var x.r a.r.c x.r; end
|
||||
end
|
||||
Arows=r-1; Acols=c-1
|
||||
y.=
|
||||
y.1 = 1 2 3 /*if all values are positive, */
|
||||
y.2 = 4 5 6 /*can eliminate the quotes. */
|
||||
do r=1 while y.r\=='' /*build the "B" matric from Y. #s*/
|
||||
do c=1 while y.r\==''; parse var y.r b.r.c y.r; end
|
||||
end
|
||||
Brows=r-1; Bcols=c-1
|
||||
c.=0; L=0 /*L is max width of an element. */
|
||||
do i =1 for Arows /*multiply matrix A & B ──<E29480> C */
|
||||
do j =1 for Bcols
|
||||
do k=1 for Acols
|
||||
c.i.j = c.i.j + a.i.k * b.k.j; L=max(L,length(c.i.j))
|
||||
end /*k*/
|
||||
end /*j*/
|
||||
end /*i*/
|
||||
|
||||
call showMat 'A', Arows, Acols
|
||||
call showMat 'B', Brows, Bcols
|
||||
call showMat 'C', Arows, Bcols
|
||||
exit /*stick a fork in it, we're done.*/
|
||||
/*──────────────────────────────────SHOWMAT subroutine──────────────────*/
|
||||
showMat: parse arg mat,rows,cols; say
|
||||
say center(mat 'matrix',cols*(L+1)+4,"─")
|
||||
do r =1 for rows; _=
|
||||
do c=1 for cols; _=_ right(value(mat'.'r'.'c),L); end; say _
|
||||
end
|
||||
return
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
(define (m-mult m1 m2)
|
||||
(for/list ([r m1])
|
||||
(for/list ([c (apply map list m2)])
|
||||
(apply + (map * r c)))))
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
#lang racket
|
||||
(require math)
|
||||
(matrix* (matrix [[1 2]
|
||||
[3 4]])
|
||||
(matrix [[5 6]
|
||||
[7 8]]))
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
require 'matrix'
|
||||
|
||||
Matrix[[1, 2],
|
||||
[3, 4]] * Matrix[[-3, -8, 3],
|
||||
[-2, 1, 4]]
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
def matrix_mult(a, b)
|
||||
a.map do |ar|
|
||||
b.transpose.map do |bc|
|
||||
ar.zip(bc).map {|x,y| x*y}.inject {|z,w| z+w}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
def mult[A](a: Array[Array[A]], b: Array[Array[A]])(implicit n: Numeric[A]) = {
|
||||
import n._
|
||||
for (row <- a)
|
||||
yield for(col <- b.transpose)
|
||||
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
def mult[A, CC[X] <: Seq[X], DD[Y] <: Seq[Y]](a: CC[DD[A]], b: CC[DD[A]])
|
||||
(implicit n: Numeric[A]): CC[DD[A]] = {
|
||||
import n._
|
||||
for (row <- a)
|
||||
yield for(col <- b.transpose)
|
||||
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
(define (matrix-multiply matrix1 matrix2)
|
||||
(map
|
||||
(lambda (row)
|
||||
(apply map
|
||||
(lambda column
|
||||
(apply + (map * row column)))
|
||||
matrix2))
|
||||
matrix1))
|
||||
20
Task/Matrix-multiplication/Tcl/matrix-multiplication.tcl
Normal file
20
Task/Matrix-multiplication/Tcl/matrix-multiplication.tcl
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
package require Tcl 8.5
|
||||
namespace path ::tcl::mathop
|
||||
proc matrix_multiply {a b} {
|
||||
lassign [size $a] a_rows a_cols
|
||||
lassign [size $b] b_rows b_cols
|
||||
if {$a_cols != $b_rows} {
|
||||
error "incompatible sizes: a($a_rows, $a_cols), b($b_rows, $b_cols)"
|
||||
}
|
||||
set temp [lrepeat $a_rows [lrepeat $b_cols 0]]
|
||||
for {set i 0} {$i < $a_rows} {incr i} {
|
||||
for {set j 0} {$j < $b_cols} {incr j} {
|
||||
set sum 0
|
||||
for {set k 0} {$k < $a_cols} {incr k} {
|
||||
set sum [+ $sum [* [lindex $a $i $k] [lindex $b $k $j]]]
|
||||
}
|
||||
lset temp $i $j $sum
|
||||
}
|
||||
}
|
||||
return $temp
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue