Skip to content

Vector

Create

Action Code Details
From matrix
to_vector(m)
Type of vector depends on shape of the matrix?
From 1D array
real a[] = {1, 2};
to_vector(a)

Create column vector

Action Code Details
Declare column vector of size N
vector[N] v;
Declare column vector with values
vector[3] v = [3, 5, 7]'
Declare column vector filled with zeros
vector[N] v = rep_vector(0, N);
Declare column vector filled with value
vector[N] v = rep_vector(value, N);

Create row vector

Action Code Details
Declare row vector of size N
row_vector[N] v;
Declare row vector with values
row_vector[3] v = [3, 5, 7];

Create special vectors with constraints

Action Code Details
Declare ordered vector of size N
ordered[N] v;
Declare positive ordered vector of size N
positive_ordered[N] v;
Declare simplex of size N (proportions vector that sum up to 1)
simplex[N] theta;
Declare unit vector
unit_vector[N] theta;
Declare optional vector in parameter block, conditional on include
vector[include ? N : 0] v;
Useful for disabling model feature to save memory

Properties

Action Code Details
Length (number of elements)
num_elements(v)

Extract

Action Code Details
Get element at index i
v[i]
Get element at index i as vector
rep_vector(v[i], 1)
Get index of largest value
int which_max(vector x) {
    real max_x = max(x);
    int i = 0;
    while (x[i] != max_x) {
      i += 1;
    }
    return i;
}

which_max(v)

Derive

Map

Element-wise operations.

Action Code Details
Square elements
square(v)
Square root elements
sqrt(v)
Different multiplication per element
v .* w
Different power per element
exp(p * log(v))
only for strictly positive v
Different power per element
N = num_elements(v);
vector c[N];
for (i in 1:N) {
  c[i] = v[i] ^ p[i];
}
Cumulative sum
cumulative_sum(v)
Softmax
softmax(v)
Log-softmax
log_softmax(v)
Dot product
v * w
Dot product (self)
dot_self(v)
v * v, or sum(v .* v)
Dot product
dot_product(v, w)

Grow

Action Code Details
Append element to column vector
append_row(v, x)
Prepend element to column vector
append_row(x, v)
Append element to row vector
append_col(v, x)
Prepend element to row vector
append_col(x, v)

Shrink

Action Code Details
First n elements (head)
head(v, n)
Last n elements (tail)
tail(v, n)
Slice
v[start:end]
Slice of length n
segment(v, start, n)

Reshape

Action Code Details
Transpose
v'

Convert

Action Code Details
To row vector
to_row_vector(v)
Transpose: from row to column vector, or vice versa
v'
To n by m matrix, column-major order
to_matrix(v, nrow, ncol)
To matrix with 1 row or column
to_matrix(v)
Depends on whether v is a row or column vector
To 1D array
to_array_1d(v)