Write a VBA function (named “MultMatrix”, of type “Variant”) to calculate the pr
ID: 670693 • Letter: W
Question
Write a VBA function (named “MultMatrix”, of type “Variant”) to
calculate the product of two arbitrary matrices in an Excel spreadsheet. Your function should
flag incompatible matrices for multiplication with a “Message Box”. For the following 3 x 3
matrices calculate A*B = C, check your results against the MMULT function in Excel.
(3x3)
A =
5 7 2
1 1 -1
8 8 5
B =
8 -2 3
2 2 4
3 4 1
• The two matrices being multiplied are “Range” arguments to the function; you can access
their sizes with the VBA constructs “.Rows.Count” and “.Columns.Count”. The individual
array elements are accessed with the “.Cells(i,j)” construct.
• The matrix C does not necessarily have the same dimensions as A or B. You may want to
declare the size of the C matrix to do the computations. One possibility is to use dynamically
allocated arrays (see section 2.13 of the Law text, pp 39-42).
Explanation / Answer
Function MatrixProduct(MatrixRange1, MatrixRange2) As Double
Dim m As Integer, n As Integer
Dim i As Integer, j As Integer
Dim aRows As Integer, aCols As Integer
Dim bRows As Integer, bCols As Integer
Dim A() As Variant, B() As Variant, C() As Variant
aRows = MatrixRange1.Rows.Count
aCols = MatrixRange1.Columns.Count
bRows = MatrixRange2.Rows.Count
bCols = MatrixRange2.Columns.Count
If aRows > bRows Then
i = bRows
Else
i = aRows
End If
If aCols > bCols Then
j = bCols
Else
j = aCols
End If
ReDim A(i, j) As Variant, B(i, j) As Variant, C(i, j) As Variant
For m = 1 To i
For n = 1 To j
A(m, n) = MatrixRange1.Cells(m, n)
B(m, n) = MatrixRange2.Cells(m, n)
C(m, n) = A(m, n) * B(m, n)
Next n
Next m
MatrixProduct = C(m, n)
End Function
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.