View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.worksheet.functions
vezerid
 
Posts: n/a
Default how array functions work mmult,minverse etc

Ramki

The following code will emulate MMULT(). I have included some error
checking so that you see the code for returning an Excel error value.
The code below is not necessarily the best available but it illustrates
to some degree how ranges and variables can communicate. Further work
would require search in the .programming newsgroup. Also, for more
explicit handling of array variables inside a VBA routine the online
help on the Dim statement will be a good start.

==============

Option Base 1
Function MatrixMult(m1 As Range, m2 As Range) As Variant
Dim m 'This is the variable that will become an array and will be
returned
Dim a1, a2 'These are the variables into which we will read m1 and m2
Dim c As Range 'To be used in various checks.
' Error checking
' Any blanks or text in the cells?
For Each c In m1
If Not IsNumeric(c.Value) Or IsEmpty(c) Then
MatrixMult = CVErr(xlErrValue)
Exit Function
End If
Next c
For Each c In m2
If Not IsNumeric(c.Value) Or IsEmpty(c) Then
MatrixMult = CVErr(xlErrValue)
Exit Function
End If
Next c
' Do the two arrays have compatible dimensions?
If m1.Columns.Count < m2.Rows.Count Then
MatrixMult = CVErr(xlErrValue)
End If

' Everything OK, now the operations
' First dimensionalize the output matrix
ReDim m(m1.Rows.Count, m2.Columns.Count)
' Assign the ranges to the variables. No ReDim necessary here b/c of
assignment
a1 = m1
a2 = m2
' Now the loop to calculate the output matrix
For i = LBound(a1, 1) To UBound(a1, 1)
For j = LBound(a2, 2) To UBound(a2, 2)
tot = 0
For k = LBound(a1, 2) To UBound(a1, 2)
tot = tot + a1(i, k) * a2(k, j)
Next k
m(i, j) = tot
Next j
Next i
' Finally we assign the matrix to the function name
MatrixMult = m
End Function

<=======================

HTH
Kostis Vezerides