Subtracting two matrices

fboehlandt

Active Member
Joined
Sep 9, 2008
Messages
334
Hi everyone,
I need to perform a number of matrix calculations in VBA and intend to use Excel Worksheetfunctions for that. Unfortunately, matrix subtract is only know to .net and excel only knows the following matrix formulas:
.MMULT()
.MINVERSE()
.TRANSPOSE()
.DETERM()
I would like to subtract one matrix from another. My not very elegant workaround is the following:

ReDim subtract(1 To n, 1 To n)
For j = 1 To n
For i = 1 To n
subtract(j, i) = matrix1(j, i) - matrix2(j, i)
Next i
Next j

Both matrices are identical in size (req.) and symmetrical (if it matters). Is there a way of entering a non-descript array formula to calculate the difference of the two matrices?
 

Excel Facts

Difference between two dates
Secret function! Use =DATEDIF(A2,B2,"Y")&" years"&=DATEDIF(A2,B2,"YM")&" months"&=DATEDIF(A2,B2,"MD")&" days"
I'd impliment that code in a function. I'd probably also have the functions Plus and ScalarMult.
 
Upvote 0
The following works but I'm surprised there is no vba functionality for this:
Code:
Function MSubtract(matrix1, matrix2)
n = UBound(matrix1, 1)
m = UBound(matrix2, 1)
If n <> m Then
    MsgBox ("Input data incompatible")
    Exit Function
End If
ReDim diff(1 To n, 1 To n)
For j = 1 To n
    For i = 1 To n
        diff(j, i) = matrix1(j, i) - matrix2(j, i)
    Next i
Next j
MSubtract = diff
End Function
 
Upvote 0
MMULT etc are spreadsheet functions. On a spreadhseet, formulas like =A1-AA1 dragged, or array formulas like {=A1:E5-AA1:AE5} will do matrix subtraction.

Outside of VB, there is no need for a matrix subtraction function. In VBA for Excel, one can use Excel's spreadsheet funtions for half the job. In VB (no A), all matrix functions are all user written.
 
Upvote 0

Forum statistics

Threads
1,214,593
Messages
6,120,435
Members
448,962
Latest member
Fenes

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top