Home > Software engineering >  Generate a Matrix B, whose elements B i j are the average of row i and column j of Matrix A
Generate a Matrix B, whose elements B i j are the average of row i and column j of Matrix A

Time:12-18

I have a task to do which includes:

  1. Reading a matrix from a txt file and printing it - I managed to do this solo

  2. Generate a Matrix B, whose elements B i j are the average of row i and column j of Matrix A. Here is the prob for me. I have idea how this would happen, but I cant write it. Example: Matrix A 3 3 Matrix B ( the first element B11 should be equal to average of Row 1 of Matrix A 2 4 6 ( 2 4 6) plus average of Column 1 of Matrix A ( 2 8 6). 8 4 2 ((2 4 6) (2 8 6)) /2 and this should be applicaple for every element based on 6 8 2 its place (Element b23 is avg of sum of row 2 and column3 ) This should happen in excel VBA Thank you in advance!

This is the code i managed to do solo: your text

CodePudding user response:

The below is an example of how to create a new matrix as requested. The code includes some dummy text to read an array from a sheet (range B4:D7) then print the result to the sheet (starting in cell K4), so obviously you will want to remove those and integrate with your own code for loading the matrix. I'm assuming you are reading the array in as if it was copied from Excel, i.e. as a 2D array with each index starting at 1. It should be easy to modify for other data forms following the logic below.

Sub temp()
    'Assume A is a 1-indexed 2D array, just as if a range is copied from an Excel sheet
    Dim A As Variant
    A = Range("B4:D7").Value
    
    Dim numRows As Long
    Dim numCols As Long
    
    numRows = UBound(A, 1)
    numCols = UBound(A, 2)
    
    ReDim rowSum(1 To numCols) As Double
    ReDim colSum(1 To numRows) As Double
    
    'First we want to get the sum of each row and column
    Dim r As Long
    Dim c As Long
    For r = 1 To numRows
        For c = 1 To numCols
            rowSum(c) = rowSum(c)   A(r, c)
            colSum(r) = colSum(r)   A(r, c)
        Next
    Next
    
    'Now create the average of the row sum and column sum in each element of a new array B
    ReDim B(1 To numRows, 1 To numCols) As Double
    For r = 1 To numRows
        For c = 1 To numCols
            B(r, c) = (rowSum(c)   colSum(r)) / 2
        Next
    Next
    
    'Just for checking the results
    Range("k4").Resize(numRows, numCols) = B
End Sub
  • Related