Trouble to vectorise matrix/vector addition

Hi all. So I’m trying to speed up a model and I thought vectorising a line of code might help but I’m having troubles.

The non vectorised version is:

// Define Individual level betas - non parametric specification
for (s in 1:N_ind){
    for (dv in 1:NvarsY){
        beta0_ind[dv, s] = Zbeta0_ind[dv, s] * Tau0[dv] + Beta0[dv];
        for (iv in 1:NvarsX){
            beta_ind[dv, iv, s] = Zbeta_ind[dv, iv, s] * Tau[dv, iv] + Beta[dv, iv];
        }
    }
}

The inner loop is the line I’m trying to vectorise. My first attemp was:

beta_ind[dv, 1:NvarsX, s] = Zbeta_ind[dv, 1:NvarsX, s] * Tau[dv, 1:NvarsX] + Beta[dv, 1:NvarsX];

However this gave me an error: “No matches for: matrix + vector”

So I then tried to put a to_vector around the first term:

beta_ind[dv, 1:NvarsX, s] = to_vector(Zbeta_ind[dv, 1:NvarsX, s] * Tau[dv, 1:NvarsX]) + Beta[dv, 1:NvarsX];

But that gives me errors I don’t understand:

SAMPLING FOR MODEL ‘hierarchical_multivariate_multivariable_noncent’ NOW (CHAIN 1).
[1] “Error in sampler$call_sampler(args_list[[i]]) : "
[2] " Exception: add: Rows of m1 (9) and rows of m2 (3) must match in size (in ‘modelf203ffbde7e_hierarchical_multivariate_multivariable_noncent’ at line 37)”
error occurred during calling the sampler; sampling not done

Can anyone please advise?

You can use the rep_matrix function to copy a (row) vector into a matrix so that it can be added to another matrix. However, none of this is going to speed up your model since it compiles to essentially the same C++ either way.

1 Like

Ok thanks Ben - good to know at least!!