[英]How to do a matrix * vector multiplication and pass this result to a vector in TMB in R?
我需要做一个矩阵*向量乘法,它只生成一个数字,并将它传递给一个向量(但它在下面的注释代码中不起作用)。 到目前为止,我所拥有的是:
cpp代码
#include <TMB.hpp>
template<class Type>
Type objective_function<Type>::operator() ()
{
DATA_MATRIX(U); // id x 2 matrix
DATA_MATRIX(Z); // n x 2 matrix
matrix<Type> Z1_m1 = matrix<Type>(Z.row(0))*vector<Type>(U.row(0));
REPORT(Z1_m1); // works
vector<Type> ZZ(6);
// ZZ(0) = matrix<Type>(Z.row(0))*vector<Type>(U.row(0)); // HOW TO FIX IT??
// (This is a small code, which the real application run inside a for loop, and the row indices will be given by for)
REPORT(ZZ);
return 0;
}
R代码
require(TMB)
set.seed(232)
model_data = list(U = matrix(c(9,11,2,4), ncol = 2),
Z = matrix(c(1,2,3,4,5,6, rpois(6,2)), ncol=2))
model <- "mult"
compile(paste0(model, ".cpp"))
dyn.load(dynlib(model))
m1 = MakeADFun(data=model_data, parameters=list(),type="Fun",
checkParameterOrder=FALSE,DLL=model)
print(m1$report()) # Note: order of variables NOT the same as .cpp file
有什么帮助吗?
我已经将此问题发布到TMB 用户组。 如果解决方案首先出现在那里,我会在这里发布。
在TMB 用户组的@Bob 帮助之后,我将在这里发布我的解决方案:
#include <TMB.hpp>
template<class Type>
Type objective_function<Type>::operator() ()
{
DATA_MATRIX(U); // id x 2 matrix
DATA_MATRIX(Z); // n x 2 matrix
vector<Type> ZZ(6);
// ZZ(0) = (Z.row(0).array()*U.row(0).array()).sum();
REPORT(ZZ);
return 0;
}
这是低效的,因为它是数组元素乘法。 如果是矩阵乘法会运行得更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.