I am trying to do some calculations with arrays.

e.g. I want to solve Ax=y, so I use the following code to do so, where A is a square matrix and y is a col. vector. In VBA, A is an array with two dimension and y is one with one dimension. However, this code does not work...

x = WorksheetFunction.MMult(WorksheetFunction.MInverse(A), y)

Where did I get wrong? Thanks!

  • 3
    Define "does not work". – Oliver Charlesworth Sep 4 '11 at 23:37
  • @Oli Charlesworth It returns nothing and stop running... – BVFanZ Sep 4 '11 at 23:55
  • Nothing? No error message? Please show us code that can do that... Have you tried stepping through your code in debug mode? – Jean-François Corbett Sep 5 '11 at 12:23
  • 1
    You may find Don’t invert that matrix interesting. Be sure to read the comments too. – AakashM Sep 5 '11 at 12:40
up vote 6 down vote accepted

You can be committing one or more of many mistakes:

  • Arrays not defined as Variant (Most worksheetfunctions won't work if data type is something other than Variant).
  • Dimensions of A and y don't match up as they need to for matrix multiplication.
  • In particular, won't work if y size is (1,2) instead of (2,1) as in example below.
  • etc... Can be anything, really. You don't tell us what error message you get.

Here's an example that works:

Dim A As Variant
Dim y As Variant
Dim x As Variant

ReDim y(1 To 2, 1 To 1)
y(1, 1) = 2
y(2, 1) = 3

ReDim A(1 To 2, 1 To 2)
A(1, 1) = 3
A(2, 1) = 1
A(1, 2) = 4
A(2, 2) = 2

x = WorksheetFunction.MMult(WorksheetFunction.MInverse(A), y)
  • This is helpful. I think I committed all of the mistakes you mentioned above. BTW, the function returns no msg at all. – BVFanZ Sep 5 '11 at 18:55
  • +1 good example – brettdj Mar 10 '12 at 11:59

Let matrix A (3 x 3) be an array in Range("A1:C3"), matrix y (3 x 1) be an array in Range("E1:E3"), and matrix x (3 x 1) be an array in Range("G1:G3"). Then you can try this simple program:

Range("G1:G3") = WorksheetFunction.MMult(WorksheetFunction.MInverse(Range("A1:C3")), Range("E1:E3"))

By using the same procedure, you can do this to find the result of multiplication of a matrix (n x m) with a matrix (p x q). Of course for the simplification you should declare the variables first. I hope this answer can help you.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.