Skip to content

Instantly share code, notes, and snippets.

@tjmahr
Created June 5, 2024 18:42
Show Gist options
  • Save tjmahr/116d10669fdf463b3bbff58eeb5cd267 to your computer and use it in GitHub Desktop.
Save tjmahr/116d10669fdf463b3bbff58eeb5cd267 to your computer and use it in GitHub Desktop.
``` r
A <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), nrow = 3, ncol = 4)
B <- matrix(c(13, 14, 15, 16, 17, 18, 19, 20), nrow = 4, ncol = 2)
dot_product <- function(x, y) {
mapply(\(x, y) sum(x * y), x, y)
}
rows_of <- function(m) purrr::array_tree(m, 1)
cols_of <- function(m) purrr::array_tree(m, 2)
d <- expand.grid(rows_of(A), cols_of(B))
d
#> Var1 Var2
#> 1 1, 4, 7, 10 13, 14, 15, 16
#> 2 2, 5, 8, 11 13, 14, 15, 16
#> 3 3, 6, 9, 12 13, 14, 15, 16
#> 4 1, 4, 7, 10 17, 18, 19, 20
#> 5 2, 5, 8, 11 17, 18, 19, 20
#> 6 3, 6, 9, 12 17, 18, 19, 20
```
``` r
dot_product(d$Var1, d$Var2) |> matrix(nrow = nrow(A))
#> [,1] [,2]
#> [1,] 334 422
#> [2,] 392 496
#> [3,] 450 570
```
``` r
A %*% B
#> [,1] [,2]
#> [1,] 334 422
#> [2,] 392 496
#> [3,] 450 570
```
<sup>Created on 2024-06-05 with [reprex v2.1.0](https://reprex.tidyverse.org)</sup>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment