Correct way to add matrix to array_var_context

Say I have data:

a = 1, 2
m is a 4 x 2 matrix {{3,4},{5,6},{7,8},{9,10}}
c = 11, 12

Is this the correct way to incorporate the matrix into an array_var_context?

vector<string> names;
names.push_back("a");
names.push_back("m");
names.push_back("c");

vector<int> data;
data.push_back(1);
data.push_back(2);
data.push_back(3);
data.push_back(4);
data.push_back(5);
data.push_back(6);
data.push_back(7);
data.push_back(8);
data.push_back(9);
data.push_back(10);
data.push_back(11);
data.push_back(12);

std::vector<std::vector<size_t> > dimensions;

vector<size_t> a_dimension;
a_dimension.push_back(2);
dimensions.push_back(a_dimensions);

vector<size_t> m_dimension;
m_dimension.push_back(4);
m_dimension.push_back(2);
dimensions.push_back(m_dimension);

vector<size_t> c_dimension;
c_dimension.push_back(2);
dimensions.push_back(c_dimension);

array_var_context varContext(names, data, dimensions);

It doesn’t look wrong to me, though I’m only going by comparing it to stuff in stan/src/test/unit/io/array_var_context_test.cpp. I’m not actually familiar with what the code does. Does it not work for what you were trying to do?

It seems to work as far as not throwing any errors. I’m working on a project to use the Stan C++ code directly. The values obtained were consistent with what RStan produced until I tried a model that uses a matrix and a row_vector. The values obtained are way off, so I’m trying to figure out why.

I’d be inclined to write

for (int i = 1; i <= 12; ++i) data.push_back(i);
...
vector<size_t> m_dimension = { 4, 2 };

You have to be careful, though, because we read everything in column-major (last index first) order, even though it’s not represented that way in the underlying C++.

Thanks @Bob_Carpenter , that was my problem (I was using it as row major instead of column major). Calculated values look much better now.

1 Like