PDA

View Full Version : generic matrix multiplier



scrib3
03-22-2013, 04:42 AM
hi
im trying to write a generic matrix multiplier without using the mmult function. Any help on how i would adjust this code ive written for multiplying two 2x2 matrices? thanks :)

Sub task9()
Dim z(2, 2)
Dim y(2, 2)
Dim zy(2, 2)

For i = 1 To 2
For j = 1 To 2
z(i, j) = Range("A6").Cells(i, j)
y(i, j) = Range("D6").Cells(i, j)
Next j
Next i

For zyrow = 1 To 2
For zycolumn = 1 To 2
For zcolumn = 1 To 2
zy(zyrow, zycolumn) = zy(zyrow, zycolumn) + z(zyrow, zcolumn) * y(zcolumn, zycolumn)
Next zcolumn
Next zycolumn
Next zyrow

For i = 1 To 2
For j = 1 To 2
Range("G6").Cells(i, j) = zy(i, j)
Next j
Next i



End Sub

SamT
03-22-2013, 06:42 AM
I am just renaming thing in an effort to understand what you have. I have a hard time with names like z, y, yz

Sub task9()

Dim Matrix_1(2, 2)
Dim r1 As long, c1` As Long
Dim Matrix_2(2, 2)
Dim r2 As Long. c2 As Long

'Shouldn't Results be a 4x4 matrix?
Dim Results(2, 2)
Dim rr As Long, cr As Long

'OK, I changed the code below. It still does the same thing.
'Fill Matrixes 1 and 2 with values
Matrix_1 = Range("A6:B7")
Matrix_2 = Range("D6:7")

'No comment
For rr = 1 To 2
For cr = 1 To 2
For c1 = 1 To 2
'Shouldn't each matrix use thier own row and col indices?
Results(rr, cr) = Results(rr, cr) + Matrix_1(rr, c1) * Matrix_2(c1, cr)
Next c1
Next cr
Next rr

Range("G6") = Results

End Sub

Paul_Hossler
03-23-2013, 06:50 PM
im trying to write a generic matrix multiplier without using the mmult function.


Not sure what you mean by 'generic' but this is a user defined function that takes 2 ranges as input, and returns a 2x2 matrix as output.

The 2x2 range and the formula must be array entered (shift-control-enter) which will add the braces. Look at my blue cells


Option Explicit
Function MMultTheHardWay(RowRange As Range, ColRange As Range) As Variant
Dim iRow As Long, iCol As Long
Dim aMMult(1 To 2, 1 To 2) As Double

For iRow = 1 To 2
For iCol = 1 To 2
aMMult(iRow, iCol) = RowRange.Cells(iRow, 1) * ColRange(1, iCol)
Next iCol
Next iRow

MMultTheHardWay = aMMult
End Function



You can turn this into a Sub instead of a UDF

Paul