PDA

View Full Version : HELP needed with VBA MMULT



mattchew
04-16-2011, 02:15 AM
Hi guys,

I'm a total newbie and am trying to use mmult in VBA..
All i want to do is multiply 2 matrices (3x3 and 3x1), so that I can use that matrix for more complicated calculations.

Need help on a UDF that returns the final result as a matrix (i.e. 3x1 matrix)

Function matt()
Dim P(1 To 3, 3)
P(1, 1) = 1
P(1, 2) = 2
P(1, 3) = 3
P(2, 1) = 4
P(2, 2) = 5
P(2, 3) = 6
P(3, 1) = 7
P(3, 2) = 8
P(3, 3) = 9


Dim Q(1 To 3, 1)
Q(1, 1) = -1
Q(2, 1) = -2
Q(3, 1) = -3

Dim result(1 To 3, 1)
result = Application.WorksheetFunction.MMult(P, Q)
matt = result
End Function


Thanks in advance!!!

Matt

Paul_Hossler
04-16-2011, 05:48 AM
Might be more elegant ways


Option Explicit
Sub drv()
MsgBox matt(1, 1)
MsgBox matt(2, 1)
MsgBox matt(3, 1)

End Sub

Function matt() As Variant ' added As Variant
Dim v As Variant
Dim P(1 To 3, 1 To 3) ' 1 To 3 in both
P(1, 1) = 1
P(1, 2) = 2
P(1, 3) = 3
P(2, 1) = 4
P(2, 2) = 5
P(2, 3) = 6
P(3, 1) = 7
P(3, 2) = 8
P(3, 3) = 9


Dim Q(1 To 3, 1 To 1) ' 1 To 1
Q(1, 1) = -1
Q(2, 1) = -2
Q(3, 1) = -3

v = Application.WorksheetFunction.MMult(P, Q)

matt = v

End Function


Without the '1 To 3' and '1 To 1' the base starts at 0, to it was really a 3x4 and 3x2 array, not the 3x3 and 3x1 that MMULT wants

Paul