Home > Software design >  Calculate the matrix of square of a sum in R
Calculate the matrix of square of a sum in R

Time:10-05

I hope this is not a duplicated question. I wanted to calculate the square of a sum of a vector in a matrix form. For example, I have a vector:

v = c(a, b, c, d)

What I wanted to achieve is a matrix form of the equation expansion (a b c d)^2 = a^2 b^2 c^2 d^2 2ab 2ac 2ad 2bc 2bd 2cd as:

a^2  ab   ac   ad
ab   b^2  bc   bd
ac   bc   c^2  cd
ad   bd   cd   d^2

Is there a function in r to do so without writing it out by hand?

Thank you very much for the help.

CodePudding user response:

v = 1:4
tcrossprod(v)
#>      [,1] [,2] [,3] [,4]
#> [1,]    1    2    3    4
#> [2,]    2    4    6    8
#> [3,]    3    6    9   12
#> [4,]    4    8   12   16

Created on 2021-10-04 by the enter image description here

The above figure shows outer() and direct matrix product to be more efficient than tcrossprod()

  • Related