Monday, July 22, 2019

Excel VBA : General Purpose Linear Equation Solver

So simple, I'm surprised this one's not there online someplace already. If you read my older post, you might wonder why this one doesn't need the ".Transpose" thingie. Answer - coz you're feeding it a column vector and Excel is smart enough - for a change :)

Give these a quick browse first for the why - unless you know why already :)
https://stackoverflow.com/questions/23443361/matrix-math-with-vba-system-of-linear-equations
https://www.ozgrid.com/forum/forum/help-forums/excel-general/12863-solve-linear-equations

Point : if you know what you're doing, you have your coefficients in one matrix and the right-hand-side in a column vector and you want to fire a weapon..


You have to select a bunch of cells, enter the formula and hit CTRL-SHIFT-ENTER (see older post)

But, this function could be used within VBA itself - these pictures are just to show what you get.. You don't *have* to use it this way putting the inputs and outputs in cells..

Function solve_lin(coeff As Variant, RHS As Variant) As Variant
    Dim retVal As Variant
   
    retVal = Application.WorksheetFunction.MMult(Application.WorksheetFunction.MInverse(coeff), RHS)
   
    solve_lin = retVal

End Function

Or, since you're most likely to send it a row vector :)
Function solve_lin(coeff As Variant, RHS As Variant) As Variant
    Dim retVal As Variant
   
    retVal = Application.WorksheetFunction.MMult(Application.WorksheetFunction.MInverse(coeff), Application.WorksheetFunction.Transpose(RHS))
   
    solve_lin = retVal
End Function

No comments: