constructing a matrix in excel vba

33,655

There are a number of basic problems with your code, which you should clear up before progressing. See comments in code below:

Sub Matrix()
    ' declare ALL your variables
    Dim n As Long, m As Long
    Dim ws As Worksheet

    ' specify type for all variables, otherwise they will be Variant
    Dim Sigmai As Single, Sigmaj As Single, Rho As Single

    ' Explicitly reference the required sheet
    Set ws = Sheet1 ' or ActiveSheet or whatever

    ' qualify range references with worksheet
    Sigmai = ws.Range("b12").Value
    Sigmaj = ws.Range("b13").Value
    Rho = ws.Range("b14").Value

    ' Specify required lower bound. Default base is 0
    Dim matrixelement(1 To 10, 1 To 10) As Single
    For n = 1 To 10
        For m = 1 To 10
            matrixelement(n, m) = Sigmai * Sigmaj * Rho
        Next m
    Next n

    ' return result to sheet in one go
    ws.Range("A1:J10") = matrixelement

End Sub

For the

And the last thing I want to do is to multiply that matrix by the transpose of that matrix

part, I not sure what you are after exactly, but MMULT may be usefull, eg

ws.Range("L1:U10") = Application.WorksheetFunction.MMult(matrixelement, matrixelement)
Share:
33,655
user1525225
Author by

user1525225

Updated on July 09, 2022

Comments

  • user1525225
    user1525225 almost 2 years

    I need help in constructing a n x n matrix, where n is equal to the number of remaining stocks at time t for t = 0, ..., 10. Initially, I have in total 10 stocks, which I will discard one by one as time goes by.

    Each element of the matrix will be equal to sigma(i) x sigma (j) x rho , where sigma(i)=sigma(j) = 0.25 and rho=0.2

    And the last thing I want to do is to multiply that matrix by the transpose of that matrix

    I am really confused where and how to start, and really thankful for your help

    Sub Matrix() 
    'Sigmai 'Sigmaj 'Rho 
        Dim Sigmai, Sigmaj, Rho As Single 
        Sigmai = Range("b12").Value 
        Sigmaj = Range("b13").Value 
        Rho = Range("b14").Value 
        Dim matrixelement(10, 10) As Single 
        For n = 1 To 10 
            For m = 1 To 10 
                matrixelement(n, m) = Sigmai * Sigmaj * Rho 
                Cells(n, m) = matrixelement(n, m) 
            Next m 
        Next n 
    End Sub