Scalar-Matrix multiplication

I’m struggling to do matrix-scalar multiplication in Stan. Is it not possible to scale all matrix elements by the same scalar value in stan? Is this done a different way?

data {
  int K; //outcome classes
  int N; //rows
  int D; //input dimensions
  int y[N];
  matrix[N, D] X;
  real days[N]; 
}
parameters {
  matrix[D, K] C;
  matrix[D, K] B;
}
model {
  matrix[N, K] pred = X*C + days*X*B; // remove days and it compiles fine.

  to_vector(pred) ~ normal(0, 5);

  for (n in 1:N)
    y[n] ~ categorical_logit(pred[n]');
}

Edit: My data looks like:

index, curr_1, curr_2, curr_3, days, end
0,          1,      0,      0,    0,   2
1,          0,      2,      0,    1,   2  

Well, days is not a scalar, it’s an array. I take it you want to multiply each row of X by the corresponding element of days? Specialized matrix product functions can help.

data {
  ...
  vector[N] days; // vector instead of array
}
...
model {
  // interprete days as a diagnoal matrix, multiply with X
  matrix[N, K] pred = X*C + diag_pre_multiply(days,X)*B;
  ...
}
1 Like

@nhuurre, that’s not quite what I’m describing. So with days excluded for simplicity, the one-hot nature of returns the following arrays:

// X      * C                + X       *  B
[1,0,0] * [[c11, c12, c13],  + [1,0,0] * [[b11, b12, b13],  
           [c21, c22, c23],               [b21, b22, b23],
           [c21, c22, c23]]               [b31, b32, b33]]
= [c11, c12, c13] + [b11, b12, b13] 

I simply want to scale every element in X*B by the same scalar value:

days * [b11, b12, b13] = [days*b11, days*b12, days*b13]

This is a trivial task in Numpy; I’m not sure I understand why it’s not intuitive with Stan.

What I want with days included is: X*C + days * X*B* where daysscales every vector element inX*B`.

Hopefully this makes sense!

In your model X is an N\times D matrix but then you show X=[1,0,0] which is a row vector. So is N=1 in this example? If so, the code I gave does what you show.