Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Matrix_multiplication
note: Matrices

View file

@ -0,0 +1,6 @@
;Task:
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.
<br><br>

View file

@ -0,0 +1,34 @@
F matrix_mul(m1, m2)
assert(m1[0].len == m2.len)
V r = [[0.0] * m2[0].len] * m1.len
L(j) 0 .< m1.len
L(i) 0 .< m2[0].len
V s = 0.0
L(k) 0 .< m2.len
s += m1[j][k] * m2[k][i]
r[j][i] = s
R r
F to_str(m)
V result = ([
L(r) m
I result.len > 2
result = "]\n ["
L(val) r
result = #5.2.format(val)
R result])
V a = [[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]]
V b = [[ 4.0, -3.0 , 4/3.0, -1/4.0],
[-13/3.0, 19/4.0, -7/3.0, 11/24.0],
[ 3/2.0, -2.0 , 7/6.0, -1/4.0],
[ -1/6.0, 1/4.0, -1/6.0, 1/24.0]]
print(to_str(a))
print(to_str(b))
print(to_str(matrix_mul(a, b)))
print(to_str(matrix_mul(b, a)))

View file

@ -0,0 +1,106 @@
* Matrix multiplication 06/08/2015
MATRIXRC CSECT Matrix multiplication
USING MATRIXRC,R13
SAVEARA B STM-SAVEARA(R15)
DC 17F'0'
STM STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
LA R7,1 i=1
LOOPI1 CH R7,M do i=1 to m (R7)
BH ELOOPI1
LA R8,1 j=1
LOOPJ1 CH R8,P do j=1 to p (R8)
BH ELOOPJ1
LR R1,R7 i
BCTR R1,0
MH R1,P
LR R6,R8 j
BCTR R6,0
AR R1,R6
SLA R1,2
LA R6,0
ST R6,C(R1) c(i,j)=0
LA R9,1 k=1
LOOPK1 CH R9,N do k=1 to n (R9)
BH ELOOPK1
LR R1,R7 i
BCTR R1,0
MH R1,P
LR R6,R8 j
BCTR R6,0
AR R1,R6
SLA R1,2
L R2,C(R1) R2=c(i,j)
LR R10,R1 R10=offset(i,j)
LR R1,R7 i
BCTR R1,0
MH R1,N
LR R6,R9 k
BCTR R6,0
AR R1,R6
SLA R1,2
L R3,A(R1) R3=a(i,k)
LR R1,R9 k
BCTR R1,0
MH R1,P
LR R6,R8 j
BCTR R6,0
AR R1,R6
SLA R1,2
L R4,B(R1) R4=b(k,j)
LR R15,R3 a(i,k)
MR R14,R4 a(i,k)*b(k,j)
LR R3,R15
AR R2,R3 R2=R2+a(i,k)*b(k,j)
ST R2,C(R10) c(i,j)=c(i,j)+a(i,k)*b(k,j)
LA R9,1(R9) k=k+1
B LOOPK1
ELOOPK1 LA R8,1(R8) j=j+1
B LOOPJ1
ELOOPJ1 LA R7,1(R7) i=i+1
B LOOPI1
ELOOPI1 MVC Z,=CL80' ' clear buffer
LA R7,1
LOOPI2 CH R7,M do i=1 to m
BH ELOOPI2
LA R8,1
LOOPJ2 CH R8,P do j=1 to p
BH ELOOPJ2
LR R1,R7 i
BCTR R1,0
MH R1,P
LR R6,R8 j
BCTR R6,0
AR R1,R6
SLA R1,2
L R6,C(R1) c(i,j)
LA R3,Z
AH R3,IZ
XDECO R6,W
MVC 0(5,R3),W+7 output c(i,j)
LH R3,IZ
LA R3,5(R3)
STH R3,IZ
LA R8,1(R8) j=j+1
B LOOPJ2
ELOOPJ2 XPRNT Z,80 print buffer
MVC IZ,=H'0'
LA R7,1(R7) i=i+1
B LOOPI2
ELOOPI2 L R13,4(0,R13)
LM R14,R12,12(R13)
XR R15,R15
BR R14
A DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8' a(4,2)
B DC F'1',F'2',F'3',F'4',F'5',F'6' b(2,3)
C DS 12F c(4,3)
N DC H'2' dim(a,2)=dim(b,1)
M DC H'4' dim(a,1)
P DC H'3' dim(b,2)
Z DS CL80
IZ DC H'0'
W DS CL16
YREGS
END MATRIXRC

View file

@ -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$)
)

View file

@ -0,0 +1,10 @@
x +.×
A A*¨A4 ⍝ 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

View file

@ -0,0 +1,54 @@
# Usage: GAWK -f MATRIX_MULTIPLICATION.AWK filename
# Separate matrices a and b by a blank line
BEGIN {
ranka1 = 0; ranka2 = 0
rankb1 = 0; rankb2 = 0
matrix = 1 # Indicate first (1) or second (2) matrix
i = 0
}
NF == 0 {
if (++matrix > 2) {
printf("Warning: Ignoring data below line %d.\n", NR)
}
i = 0
next
}
{
# Store first matrix in a, second matrix in b
if (matrix == 1) {
ranka1 = ++i
ranka2 = max(ranka2, NF)
for (j = 1; j <= NF; j++)
a[i,j] = $j
}
if (matrix == 2) {
rankb1 = ++i
rankb2 = max(rankb2, NF)
for (j = 1; j <= NF; j++)
b[i,j] = $j
}
}
END {
# Check ranks of a and b
if ((ranka1 < 1) || (ranka2 < 1) || (rankb1 < 1) || (rankb2 < 1) ||
(ranka2 != rankb1)) {
printf("Error: Incompatible ranks (%dx%d)*(%dx%d).\n", ranka1, ranka2, rankb1, rankb2)
exit
}
# Multiplication c = a * b
for (i = 1; i <= ranka1; i++) {
for (j = 1; j <= rankb2; j++) {
c[i,j] = 0
for (k = 1; k <= ranka2; k++)
c[i,j] += a[i,k] * b[k,j]
}
}
# Print matrix c
for (i = 1; i <= ranka1; i++) {
for (j = 1; j <= rankb2; j++)
printf("%g%s", c[i,j], j < rankb2 ? " " : "\n")
}
}
function max(m, n) {
return m > n ? m : n
}

View file

@ -0,0 +1,80 @@
INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
DEFINE PTR="CARD"
TYPE Matrix=[
BYTE width,height
PTR data] ;INT ARRAY
PROC PrintMatrix(Matrix POINTER m)
BYTE i,j
INT ARRAY d
CHAR ARRAY s(10)
d=m.data
FOR j=0 TO m.height-1
DO
FOR i=0 TO m.width-1
DO
StrI(d(j*m.width+i),s)
PrintF("%2S ",s)
OD
PutE()
OD
RETURN
PROC Create(MATRIX POINTER m BYTE w,h INT ARRAY a)
m.width=w
m.height=h
m.data=a
RETURN
PROC MatrixMul(Matrix POINTER m1,m2,res)
BYTE i,j,k
INT ARRAY d1,d2,dres,sum
IF m1.width#m2.height THEN
Print("Invalid size of matrices for multiplication!")
Break()
FI
d1=m1.data
d2=m2.data
dres=res.data
res.width=m2.width
res.height=m1.height
FOR j=0 TO res.height-1
DO
FOR i=0 TO res.width-1
DO
sum=0
FOR k=0 TO m1.width-1
DO
sum==+d1(k+j*m1.width)*d2(i+k*m2.width)
OD
dres(j*res.width+i)=sum
OD
OD
RETURN
PROC Main()
MATRIX m1,m2,res
INT ARRAY
d1=[2 1 4 0 1 1],
d2=[6 3 65535 0 1 1 0 4 65534 5 0 2],
dres(8)
Put(125) PutE() ;clear the screen
Create(m1,3,2,d1)
Create(m2,4,3,d2)
Create(res,0,0,dres)
MatrixMul(m1,m2,res)
PrintMatrix(m1)
PutE() PrintE("multiplied by") PutE()
PrintMatrix(m2)
PutE() PrintE("equals") PutE()
PrintMatrix(res)
RETURN

View 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;

View 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;

View file

@ -0,0 +1,7 @@
#include <hopper.h>
main:
first matrix=0, second matrix=0,a=-1
{5,2},rand array(a),mulby(10),ceil, cpy(first matrix), puts,{"\n"},puts
{2,3},rand array(a),mulby(10),ceil, cpy(second matrix), puts,{"\n"},puts
{first matrix,second matrix},mat mul, println
exit(0)

View file

@ -0,0 +1,7 @@
#include <natural.h>
#include <hopper.h>
main:
get a matrix of '5,2' integer random numbers, remember it in 'first matrix' and put it with a newline
get a matrix of '2,3' integer random numbers, remember it in 'second matrix' and put it with a newline
now take 'first matrix', and take 'second matrix', and multiply it; then, print with a new line.
exit(0)

View file

@ -0,0 +1,159 @@
--------------------- MATRIX MULTIPLY --------------------
-- matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]]
to matrixMultiply(a, b)
script rows
property xs : transpose(b)
on |λ|(row)
script columns
on |λ|(col)
my dotProduct(row, col)
end |λ|
end script
map(columns, xs)
end |λ|
end script
map(rows, a)
end matrixMultiply
--------------------------- TEST -------------------------
on run
matrixMultiply({¬
{-1, 1, 4}, ¬
{6, -4, 2}, ¬
{-3, 5, 0}, ¬
{3, 7, -2} ¬
}, {¬
{-1, 1, 4, 8}, ¬
{6, 9, 10, 2}, ¬
{11, -4, 5, -3}})
--> {{51, -8, 26, -18}, {-8, -38, -6, 34},
-- {33, 42, 38, -14}, {17, 74, 72, 44}}
end run
-------------------- GENERIC FUNCTIONS -------------------
-- dotProduct :: [n] -> [n] -> Maybe n
on dotProduct(xs, ys)
script mult
on |λ|(a, b)
a * b
end |λ|
end script
if length of xs is not length of ys then
missing value
else
sum(zipWith(mult, xs, ys))
end if
end dotProduct
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldr
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- product :: Num a => [a] -> a
on product(xs)
script mult
on |λ|(a, b)
a * b
end |λ|
end script
foldr(mult, 1, xs)
end product
-- sum :: Num a => [a] -> a
on sum(xs)
script add
on |λ|(a, b)
a + b
end |λ|
end script
foldr(add, 0, xs)
end sum
-- transpose :: [[a]] -> [[a]]
on transpose(xss)
script column
on |λ|(_, iCol)
script row
on |λ|(xs)
item iCol of xs
end |λ|
end script
map(row, xss)
end |λ|
end script
map(column, item 1 of xss)
end transpose
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith

View file

@ -0,0 +1 @@
{{51, -8, 26, -18}, {-8, -38, -6, 34}, {33, 42, 38, -14}, {17, 74, 72, 44}}

View file

@ -0,0 +1,9 @@
1 FOR K = 0 TO 1:M = O:N = P: READ O,P: IF K THEN DIM B(O,P): IF N < > O THEN PRINT "INVALID DIMENSIONS": STOP
2 IF NOT K THEN DIM A(O,P)
3 FOR I = 1 TO O: FOR J = 1 TO P: IF K THEN READ B(I,J)
4 IF NOT K THEN READ A(I,J)
5 NEXT J,I,K: DIM AB(M,P): FOR I = 1 TO M: FOR J = 1 TO P: FOR K = 1 TO N:AB(I,J) = AB(I,J) + (A(I,K) * B(K,J)): NEXT K,J,I: FOR I = 1 TO M: FOR J = 1 TO P: PRINT MID$ (S$,1 + (J = 1),1)AB(I,J);:S$ = " " + CHR$ (13): NEXT J,I
10000 DATA4,2
10010 DATA1,2,3,4,5,6,7,8
20000 DATA2,3
20010 DATA1,2,3,4,5,6

View file

@ -0,0 +1,14 @@
DIM matrix1(4,2),matrix2(2,3)
MAT READ matrix1
DATA 1,2
DATA 3,4
DATA 5,6
DATA 7,8
MAT READ matrix2
DATA 1,2,3
DATA 4,5,6
MAT product=matrix1*matrix2
MAT PRINT product

View file

@ -0,0 +1,33 @@
printMatrix: function [m][
loop m 'row -> print map row 'val [pad to :string .format:".2f" val 6]
print "--------------------------------"
]
multiply: function [a,b][
X: size a
Y: size first b
result: array.of: @[X Y] 0
loop 0..X-1 'i [
loop 0..Y-1 'j [
loop 0..(size first a)-1 'k ->
result\[i]\[j]: result\[i]\[j] + a\[i]\[k] * b\[k]\[j]
]
]
return result
]
A: [[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: @[@[ 4.0 0-3.0 4/3.0 0-1/4.0]
@[0-13/3.0 19/4.0 0-7/3.0 11/24.0]
@[ 3/2.0 0-2.0 7/6.0 0-1/4.0]
@[ 0-1/6.0 1/4.0 0-1/6.0 1/24.0]]
printMatrix A
printMatrix B
printMatrix multiply A B
printMatrix multiply B A

View file

@ -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
}
}
}

View file

@ -0,0 +1,15 @@
Multiply_Matrix(A,B){
if (A[1].Count() <> B.Count())
return ["Dimension Error"]
R := [], RRows := A.Count(), RCols:= b[1].Count()
Loop, % RRows {
RRow:=A_Index
loop, % RCols {
RCol:=A_Index, v := 0
loop % A[1].Count()
col := A_Index, v += A[RRow, col] * B[col, RCol]
R[RRow,RCol] := v
}
}
return R
}

View file

@ -0,0 +1,19 @@
A := [[1,2]
, [3,4]
, [5,6]
, [7,8]]
B := [[1,2,3]
, [4,5,6]]
if Res := Multiply_Matrix(A,B)
MsgBox % Print(Res)
else
MsgBox Error
return
Print(M){
for i, row in M
for j, col in row
Res .= (A_Index=1?"":"`t") col (Mod(A_Index,M[1].MaxIndex())?"":"`n")
return Trim(Res,"`n")
}

View file

@ -0,0 +1,24 @@
Assume the matrices to be multiplied are a and b
IF (LEN(a,2) = LEN(b)) 'if valid dims
n = LEN(a,2)
m = LEN(a)
p = LEN(b,2)
DIM ans(0 TO m - 1, 0 TO p - 1)
FOR i = 0 TO m - 1
FOR j = 0 TO p - 1
FOR k = 0 TO n - 1
ans(i, j) = ans(i, j) + (a(i, k) * b(k, j))
NEXT k, j, i
'print answer
FOR i = 0 TO m - 1
FOR j = 0 TO p - 1
PRINT ans(i, j);
NEXT j
PRINT
NEXT i
ELSE
PRINT "invalid dimensions"
END IF

View file

@ -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

View file

@ -0,0 +1,11 @@
Mul +˝×1
(>
1, 2, 3
4, 5, 6
7, 8, 9
) Mul >
1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12

View file

@ -0,0 +1,5 @@
20 23 26 29
56 68 80 92
92 113 134 155

View file

@ -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

View 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;
}

View 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() */

View 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 */

View file

@ -0,0 +1,62 @@
#include <stdio.h>
#define MAT_ELEM(rows,cols,r,c) (r*cols+c)
//Improve performance by assuming output matrices do not overlap with
//input matrices. If this is C++, use the __restrict extension instead
#ifdef __cplusplus
typedef double * const __restrict MAT_OUT_t;
#else
typedef double * const restrict MAT_OUT_t;
#endif
typedef const double * const MAT_IN_t;
static inline void mat_mult(
const int m,
const int n,
const int p,
MAT_IN_t a,
MAT_IN_t b,
MAT_OUT_t c)
{
for (int row=0; row<m; row++) {
for (int col=0; col<p; col++) {
c[MAT_ELEM(m,p,row,col)] = 0;
for (int i=0; i<n; i++) {
c[MAT_ELEM(m,p,row,col)] += a[MAT_ELEM(m,n,row,i)]*b[MAT_ELEM(n,p,i,col)];
}
}
}
}
static inline void mat_show(
const int m,
const int p,
MAT_IN_t a)
{
for (int row=0; row<m;row++) {
for (int col=0; col<p;col++) {
printf("\t%7.3f", a[MAT_ELEM(m,p,row,col)]);
}
putchar('\n');
}
}
int main(void)
{
double a[4*4] = {1, 1, 1, 1,
2, 4, 8, 16,
3, 9, 27, 81,
4, 16, 64, 256};
double b[4*3] = { 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};
double c[4*3] = {0};
mat_mult(4,4,3,a,b,c);
mat_show(4,3,c);
return 0;
}

View file

@ -0,0 +1,65 @@
alias Matrix => Integer[][];
void printMatrix(Matrix m) {
value strings = m.collect((row) => row.collect(Integer.string));
value maxLength = max(expand(strings).map(String.size)) else 0;
value padded = strings.collect((row) => row.collect((s) => s.padLeading(maxLength)));
for (row in padded) {
print("[``", ".join(row)``]");
}
}
Matrix? multiplyMatrices(Matrix a, Matrix b) {
function rectangular(Matrix m) =>
if (exists firstRow = m.first)
then m.every((row) => row.size == firstRow.size)
else false;
function rowCount(Matrix m) => m.size;
function columnCount(Matrix m) => m[0]?.size else 0;
if (!rectangular(a) || !rectangular(b) || columnCount(a) != rowCount(b)) {
return null;
}
function getNumber(Matrix m, Integer x, Integer y) {
assert (exists number = m[y]?.get(x));
return number;
}
function getRow(Matrix m, Integer rowIndex) {
assert (exists row = m[rowIndex]);
return row;
}
function getColumn(Matrix m, Integer columnIndex) => {
for (y in 0:rowCount(m))
getNumber(m, columnIndex, y)
};
return [
for (y in 0:rowCount(a)) [
for (x in 0:columnCount(b))
sum { 0, for ([a1, b1] in zipPairs(getRow(a, y), getColumn(b, x))) a1 * b1 }
]
];
}
shared void run() {
value m = [[1, 2, 3], [4, 5, 6]];
printMatrix(m);
print("---------");
print("multiplied by");
value m2 = [[7, 8], [9, 10], [11, 12]];
printMatrix(m2);
print("---------");
print("equals:");
value result = multiplyMatrices(m, m2);
if (exists result) {
printMatrix(result);
}
else {
print("something went wrong!");
}
}

View file

@ -0,0 +1,21 @@
proc *(a:[], b:[]) {
if (a.eltType != b.eltType) then
writeln("type mismatch: ", a.eltType, " ", b.eltType);
var ad = a.domain.dims();
var bd = b.domain.dims();
var (arows, acols) = ad;
var (brows, bcols) = bd;
if (arows != bcols) then
writeln("dimension mismatch: ", ad, " ", bd);
var c:[{arows, bcols}] a.eltType = 0;
for i in arows do
for j in bcols do
for k in acols do
c(i,j) += a(i,k) * b(k,j);
return c;
}

View file

@ -0,0 +1,25 @@
var m1:[{1..2, 1..2}] int;
m1(1,1) = 1; m1(1,2) = 2;
m1(2,1) = 3; m1(2,2) = 4;
writeln(m1);
var m2:[{1..2, 1..2}] int;
m2(1,1) = 2; m2(1,2) = 3;
m2(2,1) = 4; m2(2,2) = 5;
writeln(m2);
var m3 = m1 * m2;
writeln(m3);
var m4:[{1..2, 1..3}] int;
m4(1, 1) = 1; m4(1, 2) = 2; m4(1, 3) = 3;
m4(2, 1) = 4; m4(2, 2) = 5; m4(2, 3) = 6;
writeln(m4);
var m5:[{1..3, 1..2}] int;
m5(1, 1) = 6; m5(1, 2) = -1;
m5(2, 1) = 3; m5(2, 2) = 2;
m5(3, 1) = 0; m5(3, 2) = -3;
writeln(m5);
writeln(m4 * m5);

View 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]])

View file

@ -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)))

View file

@ -0,0 +1,6 @@
(defun matrix-multiply (matrix1 matrix2)
(mapcar
(lambda (row)
(apply #'mapcar
(lambda (&rest column)
(apply #'+ (mapcar #'* row column))) matrix2)) matrix1))

View file

@ -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))

View file

@ -0,0 +1,2 @@
(mmul #2a((1 2) (3 4)) #2a((-3 -8 3) (-2 1 4)))
#2A((-7 -6 11) (-17 -20 25))

View file

@ -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)))

View 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));
}

View file

@ -0,0 +1,16 @@
import std.stdio, std.range, std.array, std.numeric, std.algorithm;
T[][] matMul(T)(in T[][] A, in T[][] B) pure nothrow /*@safe*/ {
const Bt = B[0].length.iota.map!(i=> B.transversal(i).array).array;
return A.map!(a => Bt.map!(b => a.dotProduct(b)).array).array;
}
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, matMul(a, b));
}

View file

@ -0,0 +1,17 @@
import std.stdio, std.range, std.numeric, std.algorithm;
T[][] matMul(T)(immutable T[][] A, immutable T[][] B) pure nothrow {
immutable Bt = B[0].length.iota.map!(i=> B.transversal(i).array)
.array;
return A.map!((in a) => Bt.map!(b => a.dotProduct(b)).array).array;
}
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, matMul(a, b));
}

View file

@ -0,0 +1,33 @@
import std.stdio, std.string, std.numeric, std.algorithm, std.traits;
alias TMMul_helper(M1, M2) = Unqual!(ForeachType!(ForeachType!M1))
[M2.init[0].length][M1.length];
void matrixMul(T, T2, size_t k, size_t m, size_t n)
(in ref T[m][k] A, in ref T[n][m] B,
/*out*/ ref T2[n][k] result) pure nothrow /*@safe*/ @nogc
if (is(T2 == Unqual!T)) {
static if (hasIndirections!T)
T2[m] aux;
else
T2[m] aux = void;
foreach (immutable j; 0 .. n) {
foreach (immutable i, const ref bi; B)
aux[i] = bi[j];
foreach (immutable i, const ref ai; A)
result[i][j] = dotProduct(ai, aux);
}
}
void main() {
immutable int[2][3] a = [[1, 2], [3, 4], [3, 6]];
immutable int[3][2] b = [[-3, -8, 3,], [-2, 1, 4]];
enum form = "[%([%(%d, %)],\n %)]]";
writefln("A = \n" ~ form ~ "\n", a);
writefln("B = \n" ~ form ~ "\n", b);
TMMul_helper!(typeof(a), typeof(b)) result = void;
matrixMul(a, b, result);
writefln("A * B = \n" ~ form, result);
}

View file

@ -0,0 +1,93 @@
program Matrix_multiplication;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TMatrix = record
values: array of array of Double;
Rows, Cols: Integer;
constructor Create(Rows, Cols: Integer);
class operator Multiply(a: TMatrix; b: TMatrix): TMatrix;
function ToString: string;
end;
{ TMatrix }
constructor TMatrix.Create(Rows, Cols: Integer);
var
i: Integer;
begin
Self.Rows := Rows;
self.Cols := Cols;
SetLength(values, Rows);
for i := 0 to High(values) do
SetLength(values[i], Cols);
end;
class operator TMatrix.Multiply(a, b: TMatrix): TMatrix;
var
rows, cols, l: Integer;
i, j: Integer;
sum: Double;
k: Integer;
begin
rows := a.Rows;
cols := b.Cols;
l := a.Cols;
if l <> b.Rows then
raise Exception.Create('Illegal matrix dimensions for multiplication');
result := TMatrix.create(a.rows, b.Cols);
for i := 0 to rows - 1 do
for j := 0 to cols - 1 do
begin
sum := 0.0;
for k := 0 to l - 1 do
sum := sum + (a.values[i, k] * b.values[k, j]);
result.values[i, j] := sum;
end;
end;
function TMatrix.ToString: string;
var
i, j: Integer;
begin
Result := '[';
for i := 0 to 2 do
begin
if i > 0 then
Result := Result + #10;
Result := Result + '[';
for j := 0 to 2 do
begin
if j > 0 then
Result := Result + ', ';
Result := Result + format('%5.2f', [values[i, j]]);
end;
Result := Result + ']';
end;
Result := Result + ']';
end;
var
a, b, r: TMatrix;
i, j: Integer;
begin
a := TMatrix.Create(3, 3);
b := TMatrix.Create(3, 3);
a.values := [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
b.values := [[2, 2, 2], [5, 5, 5], [7, 7, 7]];
r := a * b;
Writeln('a: ');
Writeln(a.ToString, #10);
Writeln('b: ');
Writeln(b.ToString, #10);
Writeln('a * b:');
Writeln(r.ToString);
readln;
end.

View 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

View 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

View file

@ -0,0 +1,37 @@
PROGRAM MAT_PROD
DIM A[3,1],B[1,2],ANS[3,2]
BEGIN
DATA(1,2,3,4,5,6,7,8)
DATA(1,2,3,4,5,6)
FOR I=0 TO 3 DO
FOR J=0 TO 1 DO
READ(A[I,J])
END FOR
END FOR
FOR I=0 TO 1 DO
FOR J=0 TO 2 DO
READ(B[I,J])
END FOR
END FOR
FOR I=0 TO UBOUND(ANS,1) DO
FOR J=0 TO UBOUND(ANS,2) DO
FOR K=0 TO UBOUND(A,2) DO
ANS[I,J]=ANS[I,J]+(A[I,K]*B[K,J])
END FOR
END FOR
END FOR
! print answer
FOR I=0 TO UBOUND(ANS,1) DO
FOR J=0 TO UBOUND(ANS,2) DO
PRINT(ANS[I,J],)
END FOR
PRINT
END FOR
END PROGRAM

View file

@ -0,0 +1,7 @@
open list
mmult a b = [ [ sum $ zipWith (*) ar bc \\ bc <- (transpose b) ] \\ ar <- a ]
[[1, 2],
[3, 4]] `mmult` [[-3, -8, 3],
[-2, 1, 4]]

View file

@ -0,0 +1,11 @@
def mult(m1, m2) do
Enum.map m1, fn (x) -> Enum.map t(m2), fn (y) -> Enum.zip(x, y)
|> Enum.map(fn {x, y} -> x * y end)
|> Enum.sum
end
end
end
def t(m) do # transpose
List.zip(m) |> Enum.map(&Tuple.to_list(&1))
end

View file

@ -0,0 +1,32 @@
(let ()
(defun matrices-multiply (m1 m2)
(let (fn-row-mult)
(setq fn-row-mult
(lambda (row col-idx)
(let ((col (cl-loop for m2-row in m2
collect (nth col-idx m2-row))))
(apply '+ (cl-loop for v1 in row for v2 in col
collect (* v1 v2))) ) ) )
(cl-loop for m1-row in m1 collect
(seq-map-indexed (lambda (v col-idx)
(funcall fn-row-mult m1-row col-idx) )
(nth 0 m2) ) ) ) )
(let ((m1 '((2 1 4)
(0 1 1)))
(m2 '((6 3 -1 0)
(1 1 0 4)
(-2 5 0 2)))
result-matrix)
(switch-to-buffer-other-window "**matrix-result**")
(erase-buffer)
(setq result-matrix (matrices-multiply m1 m2))
(cl-loop for line in result-matrix do
(insert (format "%s\n"
(apply 'concat
(seq-map (lambda (item) (format "%5s " item)) line) ) ) ) ) )
)

View file

@ -0,0 +1,57 @@
%% Multiplies two matrices. Usage example:
%% $ matrix:multiply([[1,2,3],[4,5,6]], [[4,4],[0,0],[1,4]])
%% If the dimentions are incompatible, an error is thrown.
%%
%% The erl shell may encode the lists output as strings. In order to prevent such
%% behaviour, BEFORE running matrix:multiply, run shell:strings(false) to disable
%% auto-encoding. When finished, run shell:strings(true) to reset the defaults.
-module(matrix).
-export([multiply/2]).
transpose([[]|_]) ->
[];
transpose(B) ->
[lists:map(fun hd/1, B) | transpose(lists:map(fun tl/1, B))].
red(Pair, Sum) ->
X = element(1, Pair), %gets X
Y = element(2, Pair), %gets Y
X * Y + Sum.
%% Mathematical dot product. A x B = d
%% A, B = 1-dimension vector
%% d = scalar
dot_product(A, B) ->
lists:foldl(fun red/2, 0, lists:zip(A, B)).
%% Exposed function. Expected result is C = A x B.
multiply(A, B) ->
%% First transposes B, to facilitate the calculations (It's easier to fetch
%% row than column wise).
multiply_internal(A, transpose(B)).
%% This function does the actual multiplication, but expects the second matrix
%% to be transposed.
multiply_internal([Head | Rest], B) ->
% multiply each row by Y
Element = multiply_row_by_col(Head, B),
% concatenate the result of this multiplication with the next ones
[Element | multiply_internal(Rest, B)];
multiply_internal([], B) ->
% concatenating and empty list to the end of a list, changes nothing.
[].
multiply_row_by_col(Row, [Col_Head | Col_Rest]) ->
Scalar = dot_product(Row, Col_Head),
[Scalar | multiply_row_by_col(Row, Col_Rest)];
multiply_row_by_col(Row, []) ->
[].

View file

@ -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

View file

@ -0,0 +1,11 @@
let MatrixMultiply (matrix1 : _[,] , matrix2 : _[,]) =
let result_row = (matrix1.GetLength 0)
let result_column = (matrix2.GetLength 1)
let ret = Array2D.create result_row result_column 0
for x in 0 .. result_row - 1 do
for y in 0 .. result_column - 1 do
let mutable acc = 0
for z in 0 .. (matrix1.GetLength 1) - 1 do
acc <- acc + matrix1.[x,z] * matrix2.[z,y]
ret.[x,y] <- acc
ret

View file

@ -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)}")
}
}

View file

@ -0,0 +1,5 @@
Array a[3,2]
Array b[2,3]
[a]:=[(2,3,5,7,11,13)]
[b]:=[(1,1,2,3,5,8)]
[a]*[b]

View file

@ -0,0 +1,14 @@
S" fsl-util.fs" REQUIRED
S" fsl/dynmem.seq" REQUIRED
: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ;
: FSQR ( F: r1 -- r2 ) FDUP F* ;
S" fsl/gaussj.seq" REQUIRED
3 3 float matrix A{{
1e 2e 3e 4e 5e 6e 7e 8e 9e 3 3 A{{ }}fput
3 3 float matrix B{{
3e 3e 3e 2e 2e 2e 1e 1e 1e 3 3 B{{ }}fput
float dmatrix C{{ \ result
A{{ 3 3 B{{ 3 3 & C{{ mat*
3 3 C{{ }}fprint

View 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

View file

@ -0,0 +1,7 @@
program mm
real , allocatable :: a(:,:),b(:,:)
integer :: l=5,m=6,n=4
a = reshape([1:l*m],[l,m])
b = reshape([1:m*n],[m,n])
print'(<n>f15.7)',transpose(matmul(a,b))
end program

View file

@ -0,0 +1,43 @@
type Matrix
dim as double m( any , any )
declare constructor ( )
declare constructor ( byval x as uinteger , byval y as uinteger )
end type
constructor Matrix ( )
end constructor
constructor Matrix ( byval x as uinteger , byval y as uinteger )
redim this.m( x - 1 , y - 1 )
end constructor
operator * ( byref a as Matrix , byref b as Matrix ) as Matrix
dim as Matrix ret
dim as uinteger i, j, k
if ubound( a.m , 2 ) = ubound( b.m , 1 ) and ubound( a.m , 1 ) = ubound( b.m , 2 ) then
redim ret.m( ubound( a.m , 1 ) , ubound( b.m , 2 ) )
for i = 0 to ubound( a.m , 1 )
for j = 0 to ubound( b.m , 2 )
for k = 0 to ubound( b.m , 1 )
ret.m( i , j ) += a.m( i , k ) * b.m( k , j )
next k
next j
next i
end if
return ret
end operator
'some garbage matrices for demonstration
dim as Matrix a = Matrix(4 , 2)
a.m(0 , 0) = 1 : a.m(0 , 1) = 0
a.m(1 , 0) = 0 : a.m(1 , 1) = 1
a.m(2 , 0) = 2 : a.m(2 , 1) = 3
a.m(3 , 0) = 0.75 : a.m(3 , 1) = -0.5
dim as Matrix b = Matrix( 2 , 4 )
b.m(0 , 0) = 3.1 : b.m(0 , 1) = 1.6 : b.m(0 , 2) = -99 : b.m (0, 3) = -8
b.m(1 , 0) = 2.7 : b.m(1 , 1) = 0.6 : b.m(1 , 2) = 0 : b.m(1,3) = 21
dim as Matrix c = a * b
print c.m(0, 0), c.m(0, 1), c.m(0, 2), c.m(0, 3)
print c.m(1, 0), c.m(1, 1), c.m(1, 2), c.m(1, 3)
print c.m(2, 0), c.m(2, 1), c.m(2, 2), c.m(2, 3)
print c.m(3, 0), c.m(3, 1), c.m(3, 2), c.m(3, 3)

View file

@ -0,0 +1,15 @@
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
}

View file

@ -0,0 +1,4 @@
fun main(x: [n][m]int, y: [m][p]int): [n][p]int =
map (fn xr => map (fn yc => reduce (+) 0 (zipWith (*) xr yc))
(transpose y))
x

View 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 ] ]

View file

@ -0,0 +1,23 @@
package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
a := mat.NewDense(2, 4, []float64{
1, 2, 3, 4,
5, 6, 7, 8,
})
b := mat.NewDense(4, 3, []float64{
1, 2, 3,
4, 5, 6,
7, 8, 9,
10, 11, 12,
})
var m mat.Dense
m.Mul(a, b)
fmt.Println(mat.Formatted(&m))
}

View file

@ -0,0 +1,28 @@
package main
import (
"fmt"
mat "github.com/skelterjohn/go.matrix"
)
func main() {
a := mat.MakeDenseMatrixStacked([][]float64{
{1, 2, 3, 4},
{5, 6, 7, 8},
})
b := mat.MakeDenseMatrixStacked([][]float64{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12},
})
fmt.Printf("Matrix A:\n%v\n", a)
fmt.Printf("Matrix B:\n%v\n", b)
p, err := a.TimesDense(b)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Product of A and B:\n%v\n", p)
}

View file

@ -0,0 +1,60 @@
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, 2, 3, 4},
[]Value{5, 6, 7, 8}}
B := Matrix{[]Value{1, 2, 3},
[]Value{4, 5, 6},
[]Value{7, 8, 9},
[]Value{10, 11, 12}}
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)
}

View file

@ -0,0 +1,56 @@
package main
import "fmt"
type matrix struct {
stride int
ele []float64
}
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("%8.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{m2.stride, make([]float64, (len(m1.ele)/m1.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 := matrix{4, []float64{
1, 2, 3, 4,
5, 6, 7, 8,
}}
b := matrix{3, []float64{
1, 2, 3,
4, 5, 6,
7, 8, 9,
10, 11, 12,
}}
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:")
}

View file

@ -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()
}
}
}

View file

@ -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()
}
}
}

View file

@ -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 }

View file

@ -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]]

View file

@ -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]

View file

@ -0,0 +1,18 @@
multiply :: Num a => [[a]] -> [[a]] -> [[a]]
multiply us vs = map (mult [] vs) us
where
mult xs [] _ = xs
mult xs _ [] = xs
mult [] (zs : zss) (y : ys) = mult (map (y *) zs) zss ys
mult xs (zs : zss) (y : ys) =
mult
(zipWith (\u v -> u + v * y) xs zs)
zss
ys
main :: IO ()
main =
mapM_ print $
multiply
[[1, 2], [3, 4]]
[[-3, -8, 3], [-2, 1, 4]]

View file

@ -0,0 +1,11 @@
mult :: Num a => [[a]] -> [[a]] -> [[a]]
mult uss vss =
let go xs
| null xs = []
| otherwise = foldl1 (zipWith (+)) xs
in go . zipWith (flip (map . (*))) vss <$> uss
main :: IO ()
main =
mapM_ print $
mult [[1, 2], [3, 4]] [[-3, -8, 3], [-2, 1, 4]]

View file

@ -0,0 +1,9 @@
import Numeric.LinearAlgebra
a, b :: Matrix I
a = (2 >< 2) [1, 2, 3, 4]
b = (2 >< 3) [-3, -8, 3, -2, 1, 4]
main :: IO ()
main = print $ a <> b

View file

@ -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)

View file

@ -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

View file

@ -0,0 +1 @@
result = arr1 # arr2

View 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

View 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

View file

@ -0,0 +1,14 @@
import Data.Vect
Matrix : Nat -> Nat -> Type -> Type
Matrix m n t = Vect m (Vect n t)
multiply : Num t => Matrix m1 n t -> Matrix n m2 t -> Matrix m1 m2 t
multiply a b = multiply' a (transpose b)
where
dot : Num t => Vect n t -> Vect n t -> t
dot v1 v2 = sum $ map (\(s1, s2) => (s1 * s2)) (zip v1 v2)
multiply' : Num t => Matrix m1 n t -> Matrix m2 n t -> Matrix m1 m2 t
multiply' (a::as) b = map (dot a) b :: multiply' as b
multiply' [] _ = []

View 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

View 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

View 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;
}

View file

@ -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));

View file

@ -0,0 +1,67 @@
(function () {
'use strict';
// matrixMultiply:: [[n]] -> [[n]] -> [[n]]
function matrixMultiply(a, b) {
var bCols = transpose(b);
return a.map(function (aRow) {
return bCols.map(function (bCol) {
return dotProduct(aRow, bCol);
});
});
}
// [[n]] -> [[n]] -> [[n]]
function dotProduct(xs, ys) {
return sum(zipWith(product, xs, ys));
}
return matrixMultiply(
[[-1, 1, 4],
[ 6, -4, 2],
[-3, 5, 0],
[ 3, 7, -2]],
[[-1, 1, 4, 8],
[ 6, 9, 10, 2],
[11, -4, 5, -3]]
);
// --> [[51, -8, 26, -18], [-8, -38, -6, 34],
// [33, 42, 38, -14], [17, 74, 72, 44]]
// GENERIC LIBRARY FUNCTIONS
// (a -> b -> c) -> [a] -> [b] -> [c]
function zipWith(f, xs, ys) {
return xs.length === ys.length ? (
xs.map(function (x, i) {
return f(x, ys[i]);
})
) : undefined;
}
// [[a]] -> [[a]]
function transpose(lst) {
return lst[0].map(function (_, iCol) {
return lst.map(function (row) {
return row[iCol];
});
});
}
// sum :: (Num a) => [a] -> a
function sum(xs) {
return xs.reduce(function (a, x) {
return a + x;
}, 0);
}
// product :: n -> n -> n
function product(a, b) {
return a * b;
}
})();

View file

@ -0,0 +1,2 @@
[[51, -8, 26, -18], [-8, -38, -6, 34],
[33, 42, 38, -14], [17, 74, 72, 44]]

View file

@ -0,0 +1,91 @@
((() => {
"use strict";
// -------------- MATRIX MULTIPLICATION --------------
// matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]]
const matrixMultiply = a =>
b => {
const cols = transpose(b);
return a.map(
compose(
f => cols.map(f),
dotProduct
)
);
};
// ---------------------- TEST -----------------------
const main = () =>
JSON.stringify(matrixMultiply(
[
[-1, 1, 4],
[6, -4, 2],
[-3, 5, 0],
[3, 7, -2]
]
)([
[-1, 1, 4, 8],
[6, 9, 10, 2],
[11, -4, 5, -3]
]));
// --------------------- GENERIC ---------------------
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// dotProduct :: Num a => [[a]] -> [[a]] -> [[a]]
const dotProduct = xs =>
// Sum of the products of the corresponding
// values in two lists of the same length.
compose(sum, zipWith(mul)(xs));
// mul :: Num a => a -> a -> a
const mul = a =>
b => a * b;
// sum :: (Num a) => [a] -> a
const sum = xs =>
xs.reduce((a, x) => a + x, 0);
// transpose :: [[a]] -> [[a]]
const transpose = rows =>
// The columns of the input transposed
// into new rows.
// Simpler version of transpose, assuming input
// rows of even length.
Boolean(rows.length) ? rows[0].map(
(_, i) => rows.flatMap(
v => v[i]
)
) : [];
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f =>
// A list constructed by zipping with a
// custom function, rather than with the
// default tuple constructor.
xs => ys => xs.map(
(x, i) => f(x)(ys[i])
).slice(
0, Math.min(xs.length, ys.length)
);
// MAIN ---
return main();
}))();

View file

@ -0,0 +1,18 @@
def dot_product(a; b):
a as $a | b as $b
| reduce range(0;$a|length) as $i (0; . + ($a[$i] * $b[$i]) );
# transpose/0 expects its input to be a rectangular matrix (an array of equal-length arrays)
def transpose:
if (.[0] | length) == 0 then []
else [map(.[0])] + (map(.[1:]) | transpose)
end ;
# A and B should both be numeric matrices, A being m by n, and B being n by p.
def multiply(A; B):
A as $A | B as $B
| ($B[0]|length) as $p
| ($B|transpose) as $BT
| reduce range(0; $A|length) as $i
([]; reduce range(0; $p) as $j
(.; .[$i][$j] = dot_product( $A[$i]; $BT[$j] ) )) ;

View file

@ -0,0 +1,18 @@
/* Matrix multiplication, in Jsish */
require('Matrix');
if (Interp.conf('unitTest')) {
var a = new Matrix([[1,2],[3,4]]);
var b = new Matrix([[-3,-8,3],[-2,1,4]]);
; a;
; b;
; a.mult(b);
}
/*
=!EXPECTSTART!=
a ==> { height:2, mtx:[ [ 1, 2 ], [ 3, 4 ] ], width:2 }
b ==> { height:2, mtx:[ [ -3, -8, 3 ], [ -2, 1, 4 ] ], width:3 }
a.mult(b) ==> { height:2, mtx:[ [ -7, -6, 11 ], [ -17, -20, 25 ] ], width:3 }
=!EXPECTEND!=
*/

View file

@ -0,0 +1,8 @@
julia> [1 2 3 ; 4 5 6] * [1 2 ; 3 4 ; 5 6] # product of a 2x3 by a 3x2
2x2 Array{Int64,2}:
22 28
49 64
julia> [1 2 3] * [1,2,3] # product of a row vector by a column vector
1-element Array{Int64,1}:
14

View file

@ -0,0 +1,3 @@
(1 2;3 4)_mul (5 6;7 8)
(19 22
43 50)

View file

@ -0,0 +1,4 @@
mul::{[a b];b::+y;{a::x;+/'{a*x}'b}'x}
[[1 2] [3 4]] mul [[5 6] [7 8]]
[[19 22]
[43 50]]

View file

@ -0,0 +1,40 @@
// version 1.1.3
typealias Vector = DoubleArray
typealias Matrix = Array<Vector>
operator fun Matrix.times(other: Matrix): Matrix {
val rows1 = this.size
val cols1 = this[0].size
val rows2 = other.size
val cols2 = other[0].size
require(cols1 == rows2)
val result = Matrix(rows1) { Vector(cols2) }
for (i in 0 until rows1) {
for (j in 0 until cols2) {
for (k in 0 until rows2) {
result[i][j] += this[i][k] * other[k][j]
}
}
}
return result
}
fun printMatrix(m: Matrix) {
for (i in 0 until m.size) println(m[i].contentToString())
}
fun main(args: Array<String>) {
val m1 = arrayOf(
doubleArrayOf(-1.0, 1.0, 4.0),
doubleArrayOf( 6.0, -4.0, 2.0),
doubleArrayOf(-3.0, 5.0, 0.0),
doubleArrayOf( 3.0, 7.0, -2.0)
)
val m2 = arrayOf(
doubleArrayOf(-1.0, 1.0, 4.0, 8.0),
doubleArrayOf( 6.0, 9.0, 10.0, 2.0),
doubleArrayOf(11.0, -4.0, 5.0, -3.0)
)
printMatrix(m1 * m2)
}

View file

@ -0,0 +1,7 @@
(defun matrix* (matrix-1 matrix-2)
(list-comp
((<- a matrix-1))
(list-comp
((<- b (transpose matrix-2)))
(lists:foldl #'+/2 0
(lists:zipwith #'*/2 a b)))))

View file

@ -0,0 +1,9 @@
> (set ma '((1 2)
(3 4)
(5 6)
(7 8)))
((1 2) (3 4) (5 6) (7 8))
> (set mb (transpose ma))
((1 3 5 7) (2 4 6 8))
> (matrix* ma mb)
((5 11 17 23) (11 25 39 53) (17 39 61 83) (23 53 83 113))

View file

@ -0,0 +1,22 @@
{require lib_matrix}
1) applying a matrix to a vector
{def M
{M.new [[1,2,3],
[4,5,6],
[7,8,-9]]}}
-> M
{def V {M.new [1,2,3]} }
-> V
{M.multiply {M} {V}}
-> [14,32,-4]
2) matrix multiplication
{M.multiply {M} {M}}
-> [[ 30, 36,-12],
[ 66, 81,-12],
[-24,-18,150]]

View file

@ -0,0 +1,2 @@
[[1 2 3] [4 5 6]] 'm dress
[[1 2] [3 4] [5 6]] 'm dress * .

View file

@ -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$

View 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}}

View 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

View file

@ -0,0 +1,5 @@
local alg = require("sci.alg")
mat1 = alg.tomat{{1, 2, 3}, {4, 5, 6}}
mat2 = alg.tomat{{1, 2}, {3, 4}, {5, 6}}
mat3 = mat1[] ** mat2[]
print(mat3)

Some files were not shown because too many files have changed in this diff Show more