简体   繁体   中英

VBA UDF correlationmatrix - not possible of taking square root (on Variant type)

I have created a function and it will return only the squared anser and it is not possible to get the right answer, which is the current anwer square rooted.

In excel my range is for example A1 = 2 & A2 = 3. If the CorrelationMatrix is set at on row one (1, 0.25) and row two (0.25, 1) the total sum when using the CorrelationMatrix is 16. The right answer is 4 (16^(0.5)).

Below the code that will get me to 16, but no way it allows me to take te square root of 16.

Function MatrixCalc(MatrixInput As Range) As Variant

    Dim MatrixCor As Variant
    MatrixCor = Array(Array(1, 0.25), Array(0.25, 1))
     
    Dim MatrixHelp As Variant
    Dim MatrixInputTr As Variant
    
    MatrixInputTr = Application.Transpose(MatrixInput.Value)
    MatrixHelp = Application.MMult(MatrixInputTr, MatrixCor)

    MatrixCalc = Application.MMult(MatrixHelp, MatrixInput)

End Function

Playing around with this with line breaks and using the immediate window, I found that the result of the first calculation is going into a single dimension Array at position 1. The sheet seems to handle this fine, the Sqr function does not.

For the second calculation, you need to modify it so that you're performing the square on specifically that array element.

Function MatrixCalc(MatrixInput As Range) As Variant

  Dim MatrixCor As Variant
  MatrixCor = Array(Array(1, 0.25), Array(0.25, 1))

  Dim MatrixHelp As Variant
  Dim MatrixInputTr As Variant

  MatrixInputTr = Application.Transpose(MatrixInput.Value)
  MatrixHelp = Application.MMult(MatrixInputTr, MatrixCor)

  ' Calculate the square root of the result
  MatrixCalc = Sqr(Application.MMult(MatrixHelp, MatrixInput.Value)(1))

End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM