# Convex combination

I would like to implement a convex combination of arbitrary length N: \sum_{i=1}^N p_i = 1 and \sum_{i=1}^N p_i x_i= 1
I tried the following code hoping that constraint would impose a convex combination constraint but stan gives me error such as sum(constraint) = z where z is a number not equal to 1.

How can this be coded? I can do it manually for N=2 without simplexes but it gets harder for N>2.

parameters {
simplex[N]  p;
real<lower=0> x[N];
}

transformed parameters {
simplex[N]  constraint;
for(c in 1:N){
constraint[n] = p[n]*x[n];
}
}


In situations like this, you want to reparameterize things so that the constraint falls entirely on a scalar.

parameters {
simplex[N] p;
simplex[N] x_unscaled;
}
transformed parameters {
simplex[N] constraint = p .* x_unscaled; // not actually a simplex yet
vector[N] x = x_unscaled / sum(constraint);
constraint /= sum(constraint); // is now a simplex that equals p .* x
}

1 Like

Perfect, thanks