Saturday, February 2, 2013

VBA: Matrix Operations

Since I still don't know how to let the user specify the "range" in a matrix, but I was eager to do something productive, here's what I came up with:

Given to Matrices, find:

1. Sum
2. Scalar Multiplication
3. Matrix Multiplication
4. Inverse
5. Transpose

I'm having difficulty with Inverse as I am having a runtime error '1004': Unable to get the MInverse property of the WorksheetFunction class. somehow, the help button doesn't work. I do know the code is correct. I just have to get why I am having such errors.


Sub MatrixPractice()
    
    matrixA = Range("A1:J10")
    matrixB = Range("L1:U10")

    
    'Count Rows and Columns
    rA = Range("A1:J10").Rows.Count
    rB = Range("L1:U10").Rows.Count
    
    cA = Range("A1:J10").Columns.Count
    cB = Range("L1:U10").Columns.Count
    
    'checker for same m x n
    If Not rA = rB And cA = cB Then
        MsgBox "can't do operations with the two matrices"
        Exit Sub
    Else
        r = rA
        c = cA
    End If
    
    'Sum
    sum = Range("B14:K23")
    Range("A13") = "Sum"
    For i = 1 To r
        For j = 1 To c
            sum(i, j) = matrixA(i, j) + matrixB(i, j)
        Next j
    Next i
    Range("B14:K23") = sum
    
    'Multiplication
    scalarM = Range("B26:K35")
    Range("A25") = "Scalar Multiplication"
    For i = 1 To r
        For j = 1 To c
            scalarM(i, j) = matrixA(i, j) * matrixB(i, j)
        Next j
    Next i
    Range("B26:K35") = scalarM
    
    'Mmult
    MMult = Application.WorksheetFunction.MMult(matrixA, matrixB)
    Range("A37") = "Matrix Multiplication"
    Range("B38:K47") = MMult
    
    'Inverse have to work on it
    'inv = Application.WorksheetFunction.MInverse(matrixB)
    'Range("A49") = "Matrix B Inverse"
    'Range("B50:K59") = inv

    'Transpose
    tran = Application.WorksheetFunction.Transpose(matrixB)
    Range("A61") = "Matrix B Transpose"
    Range("B62:K71") = tran

End Sub




No comments:

Post a Comment