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.




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