Help understanding what's happening in this code

Hello, I’m new to Stan and I have a question about something I saw when reading some research.

The model block had code that looked like this:
some_vector[1] = some_matrix[1,] * transpose(some_other_matrix[1,])

This suggests that the product of a row slice of a matrix and a transposed(row slice) is a scalar. Is this correct? Does matrix[n,] return a row_vector?

I created a code snippet that can be run in R to print what was happening:

model_code = "
data{
matrix[4,2] test_matrix;
}
transformed data{
print(test_matrix[1,]);
print(transpose(test_matrix[1,]));
print(test_matrix[1,] * transpose(test_matrix[1,]));
}
parameters{
}
model{
}
"

data = list(test_matrix=matrix(1:9, nrow = 4, ncol = 2))

stan(model_code = model_code, data = data, algorithm = 'Fixed_param', chains = 1)

Which prints:

[1,5]
[1,5]
26

If someone could lend some clarity to what’s happening, I would appreciate it! Cheers.

Yes to both, that’s correct.

Think of this as a product between a 1xN matrix and an Nx1 matrix (the Nx1 matrix comes from the 1xN transposed). The result there will be 1x1. Does that clarify things at all?

The printed output agrees with this.

1 Like

Oh maybe I interpreted this incorrectly.

Is the alternative you might expect a 1x1 matrix, but Stan gave you a scalar?

1 Like

No you got it right, I just wasn’t sure about the type of the matrix slice. In my head I was thinking product between a 1xN matrix and an Nx1 would be 1xN too, I was mistaken about that :)

Thanks for clarifying.

1 Like