sum array multiplication between columns

alex_

Registered User.
Local time
Yesterday, 20:25
Joined
Mar 24, 2012
Messages
25
Hello,

I have imported some numerical values into a 2x2 array with dimensions (n-1) rows and 5 columns, where n is an integer > 2. What I am trying to do is multiply all elements from two columns of the array, say column 4 and column 2 and sum the result. My code works, but (naturally you may think...) the result is double (x2) the expected result. Is there a way to present the calculation in a more comprehensive manner instead of taking the calculated result and divide it by two?

Code:
Dim sum As Double
Dim result As Double
        For Frow = 0 To CInt(n) - 1
            For Fcol = 4 To 4
                For yirow = 0 To CInt(n) - 1
                    For yicol = 2 To 2
                        sum += Array(Frow, Fcol) * Array(yirow, yicol)
                    Next
                Next
            Next
        Next
        result = sum
        MsgBox("Test multiplication results " & result, MsgBoxStyle.Information, "test")
    End Sub

Thank you in advance for your assistance.
 
Solution:

Please ignore the code written in the first post of mine (The nested for loop doesn't perform as intended). The solution given below assumes that the array's elements have indexes "0","n" example: second element of the second column will be 1,1. So here is the code:

Code:
' redimenion the array by adding one more column to store the product
' the initial 4 columns become 5: you can also use the ubound function
ReDim Preserve myarray(CInt(n) - 1, 5)
' declare product and sum variables
        Dim product As Double
        Dim sum As Double
' perform a For loop to calculate the product between column 4 and column 1
        For row = 0 To CInt(n) - 1
            product = myarray(row, 4) * myarray(row, 1)
' Display the calculated values to check the results. Omit the next line 
' in your code, it is only for checking
            MsgBox("Product is= " & product)
'store the product to column 5 of the array
            myarray(row, 5) = product
'close loop
        Next row
'calculate the sum of column 5 using a for loop
        For frow = 0 To CInt(n) - 1
            For fcol = 5 To 5
                sum += myarray(frow, fcol)
            Next
        Next
'Display sum of column 5 (Omit the line if not needed)
        MsgBox(sum)
 
Last edited:

Users who are viewing this thread

Back
Top Bottom