快速获取所有矩阵列元素乘积对的方法

编程入门 行业动态 更新时间:2024-10-26 04:22:10
本文介绍了快速获取所有矩阵列元素乘积对的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个数字矩阵:

set.seed(1) mat <- matrix(rnorm(1000), ncol = 100)

我想生成所有向量,这些向量是 mat 中所有唯一向量对的元素乘积的结果.

I want to generate all vectors that are the result of the element-wise product of all unique pairs of vectors in mat.

我们如何改进以下代码:

How can we improve below code:

all.pairs <- t(combn(1:ncol(mat), 2)) res <- do.call(cbind, lapply(1:nrow(all.pairs), function(p) mat[, all.pairs[p, 1]] * mat[, all.pairs[p, 2]]))

推荐答案

我们可以:

n <- ncol(mat) lst <- lapply(1:n, function (i) mat[,i] * mat[,i:n]) do.call(cbind, lst)

或者,这是一种更快的方法:

Or, here is an even faster way:

n <- ncol(mat) j1 <- rep.int(1:n, n:1) j2 <- sequence(n:1) - 1L + j1 mat[, j1] * mat[, j2]

请注意,以上将包括一列与其自身的乘法.如果你想禁止,使用

Note, the above will include the multiplication of a column to itself. If you want to forbid that, use

n <- ncol(mat) lst <- lapply(1:(n-1), function (i) mat[,i] * mat[,(i+1):n]) do.call(cbind, lst)

n <- ncol(mat) j1 <- rep.int(1:(n-1), (n-1):1) j2 <- sequence((n-1):1) + j1 mat[, j1] * mat[, j2]

实际上,上面创建的j1和j2只是combn(1:ncol(mat),2)的第一行和第二行.因此,如果您仍想继续使用 combn,请使用

Actually, j1 and j2 created above are just the 1st and 2nd row of combn(1:ncol(mat),2). So, if you still want to stay with combn, use

all.pairs <- combn(1:ncol(mat),2) mat[, all.pairs[1,]] * mat[, all.pairs[2,]]

更多推荐

快速获取所有矩阵列元素乘积对的方法

本文发布于:2023-11-30 12:18:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649918.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:乘积   矩阵   元素   快速   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!