如何进行矩阵*向量乘法并将结果传递给R中TMB中的向量?

问题描述 投票:1回答:1

我需要做一个矩阵*向量乘法,它仅生成一个数字,并将其传递给向量(但在下面的注释代码中不起作用)。我到目前为止所拥有的是:

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 users group中。如果解决方案首先出现在这里,我将其发布在这里。

c++ r rcpp tmb
1个回答
0
投票

我将在TMB Users group中的@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;
}
© www.soinside.com 2019 - 2024. All rights reserved.