Search code examples
rloopsmatrixapplymatrix-multiplication

multiple matrix generation based on vectors in R


I have an (5x4) matrix in R, namely data defined as follows:

data <- matrix(rnorm(5*4,mean=0,sd=1), 5, 4) 

and I want to create 4 different matrices that follows this formula: Assume that data[,1] = [A1,A2,A3,A4,A5]. I want to create the following matrix:

        A1*A1 A1*A2 A1*A3 A1*A4 A1*A5 
        A2*A1 A2*A2 A2*A3 A2*A4 A2*A5
   G1 = A3*A1 A3*A2 A3*A3 A3*A4 A3*A5
        A4*A1 A4*A2 A4*A3 A4*A4 A4*A5
        A5*A1 A5*A2 A5*A3 A5*A4 A5*A5

Similarly for the other columns i want to calculate at once all the G matrices (G1,G2,G3,G4). How can i achieve that?


Solution

  • results <- lapply(1:ncol(data), function(i) outer(data[, i], data[, i]))
    
    results
    
    [[1]]
             [,1]     [,2]     [,3]      [,4]      [,5]
    [1,]  0.37164  0.37582  0.33424 -0.105387  0.120936
    [2,]  0.37582  0.38006  0.33800 -0.106574  0.122298
    [3,]  0.33424  0.33800  0.30060 -0.094780  0.108765
    [4,] -0.10539 -0.10657 -0.09478  0.029885 -0.034294
    [5,]  0.12094  0.12230  0.10876 -0.034294  0.039354
    
    [[2]]
             [,1]      [,2]     [,3]     [,4]      [,5]
    [1,]  0.94684  0.117862 -1.01368  2.01456  0.719629
    [2,]  0.11786  0.014671 -0.12618  0.25077  0.089579
    [3,] -1.01368 -0.126183  1.08525 -2.15679 -0.770432
    [4,]  2.01456  0.250772 -2.15679  4.28633  1.531132
    [5,]  0.71963  0.089579 -0.77043  1.53113  0.546941
    
    [[3]]
             [,1]      [,2]      [,3]     [,4]     [,5]
    [1,]  1.61048  0.344159 -0.453466  2.68019 -0.57121
    [2,]  0.34416  0.073547 -0.096906  0.57276 -0.12207
    [3,] -0.45347 -0.096906  0.127684 -0.75467  0.16084
    [4,]  2.68019  0.572758 -0.754669  4.46044 -0.95062
    [5,] -0.57121 -0.122068  0.160837 -0.95062  0.20260
    
    [[4]]
              [,1]      [,2]      [,3]       [,4]      [,5]
    [1,]  0.559341  0.859297  0.451096 -0.0522063 -1.027929
    [2,]  0.859297  1.320109  0.693004 -0.0802028 -1.579172
    [3,]  0.451096  0.693004  0.363799 -0.0421032 -0.829002
    [4,] -0.052206 -0.080203 -0.042103  0.0048727  0.095942
    [5,] -1.027929 -1.579172 -0.829002  0.0959421  1.889075