Kartesisches Produkt zweier Matrizen A x B („A Kreuz B“)

Hi,

ich mache gerade meine ersten Schritte in der R Studio IDE und mit Base R.

Wie implementiere ich ein kartesisches Produkt von zwei Matrizen? Was muss ich in R beachten?

Danke für eure Hilfe!

Hi, I'm just doing my first steps in R Studio IDE and with Base R. How to implement a cartesian product of two matrices? What do I have to consider in R? Thank you for your help!

mat1 <- matrix(1:9, nrow = 3)
mat2 <- matrix(10:18, nrow = 3)
vec1 <- c(mat1)
vec2 <- c(mat2)
cart_prod <- expand.grid(vec1, vec2)
result <- matrix(cart_prod$Var1, nrow = nrow(mat1), byrow = TRUE)
result
#>      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
#> [1,]    1    2    3    4    5    6    7    8    9     1     2     3     4     5
#> [2,]    1    2    3    4    5    6    7    8    9     1     2     3     4     5
#> [3,]    1    2    3    4    5    6    7    8    9     1     2     3     4     5
#>      [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25] [,26]
#> [1,]     6     7     8     9     1     2     3     4     5     6     7     8
#> [2,]     6     7     8     9     1     2     3     4     5     6     7     8
#> [3,]     6     7     8     9     1     2     3     4     5     6     7     8
#>      [,27]
#> [1,]     9
#> [2,]     9
#> [3,]     9

Created on 2023-06-13 with reprex v2.0.2

Thank you! Can you provide some explanation for this solution?

I did it this way:


matrix_p <- matrix(seq(1:100),,nrow = 10)
matrix_q <- matrix(1/(seq(1:100)),byrow = TRUE,nrow = 10) 

matrix_d <- expand.grid(matrix_p, matrix_q)

1 Like

Looks good. I was extrapolating my previous experience with expand_grid() cautiously.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.