Jump to content

Matrix multiplication: Difference between revisions

m
m (Matrix Multiplication moved to Matrix multiplication: for consistency)
Line 36:
An example of user defined Vector and Matrix Multiplication Operators:
MODE FIELD = LONG REAL; # field type is LONG REAL #
INT default upb:=3;
MODE VEC = [default upb]FIELD;
MODE MAT = [default upb,default upb]FIELD;
# crude exception handling #
Line 41 ⟶ 44:
# define the vector/matrix operators #
OP * = (FLEX []FIELDVEC 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;
Line 48 ⟶ 51:
);
OP * = ([]FIELDVEC a, [,]FIELDMAT b)[]FIELDVEC: ( # overload vec 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;
Line 54 ⟶ 57:
result
);
<pre style="background-color:#ffe">
# this is the task portion #
OP * = ([,]FIELDMAT a, b)[,]FIELDMAT: ( # 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;
Line 61 ⟶ 65:
result
);
</pre>
# Some sample matrices to test #
[,]FIELDMAT a=((1, 1, 1, 1), # matrix A #
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256));
[,]FIELDMAT 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));
[,]FIELDMAT prod = a * b; # actual multiplication example of A x B #
FORMAT field fmt = $g(-6,2)$; # width of 6, with no '+' sign, 2 decimals #
FORMAT vec fmt = $"("n(2 UPB prod-1)(f(field fmt)",")f(field fmt)")"$;
FORMAT matrix fmt = $x"("n(UPB prod-1)(f(vec fmt)","lxx)f(vec fmt)");"$;
FORMAT result fmt = $x"Product of a and b: "lf(matrix fmt)l$;
FORMAT fieldreal fmt = $g(-6,2)$; # width of 6, with no '+' sign, 2 decimals #
PROC real matrix printf= (FORMAT real fmt, MAT m)VOID:(
FORMAT vec fmt = $"("n(2 UPB prodm-1)(f(fieldreal fmt)",")f(fieldreal fmt)")"$;
FORMAT matrix fmt = $x"("n(UPB prodm-1)(f(vec fmt)","lxx)f(vec fmt)");"$;
# finally print the result #
printf((resultmatrix fmt,prodm))
);
# finally print the result #
FORMAT result fmt = $xprint(("Product of a and b: "lf(matrix,new fmtline))l$;
printf((result fmt,prod))
real matrix printf(real fmt, prod)
EXIT
Cookies help us deliver our services. By using our services, you agree to our use of cookies.