r - MVM with a numeric vector (not a matrix vector) and how to avoid double transposition?
问题描述
I have the following simplified case which is actually a much bigger performance hotspot:
epsilon <- c(-3, -4)
str(epsilon)
num [1:2] -3 -4
Q <- matrix(c(2, 1, 0, 3, 1, 0), nrow=3, ncol=2)
str(Q)
num [1:3, 1:2] 2 1 0 3 1 0
Q
[,1] [,2]
[1,] 2 3
[2,] 1 1
[3,] 0 0
This is the correct result I need but it requires double-transposition i.e. expensive for large Qs:
t(epsilon*t(Q))
[,1] [,2]
[1,] -6 -12
[2,] -3 -4
[3,] 0 0
However if I simply do the following I get different results (i.e. the second row is flipped):
Q*epsilon
[,1] [,2]
[1,] -6 -12
[2,] -4 -3
[3,] 0 0
Mathematically speaking (epsilon*Q^T)^T
should be the same as Q*epsilon^T
but that's not what I want (doing Q%*%epsilon
it would generate a 3x1 result).
Is there a way to achieve this without double transposing the potentially very large Q?
解决方案
rep
提供“Q”列的索引会更容易,col
这样两个元素的长度相同
Q * epsilon[col(Q)]
或使用rep
Q * rep(epsilon, each = nrow(Q))
或与sweep
sweep(Q, 2, epsilon, `*`)
推荐阅读
- node.js - 为什么在 app.use(express.static(path.join(...))); 前面没有触发 Express Middleware
- c - 不完整的类型与大小
- rust - rust中的元组和数组有什么区别?
- c# - VSTO 模拟范围并将查询中的数据添加到模拟范围
- python - 在 python 中使用列表推导更改列表值
- java - 数字的传播输入
- rust - 如何使结构接受类型 `impl std::ops::Fn<()>` 作为其字段?
- php - 如何在 PHP 中验证仅包含空格字符的表单输入
- javascript - Ember:在控制器中获取模型数据
- c++ - 一元“运算符”未在 C++ 中定义