2
$\begingroup$

I have two vectors $\mathbf{s}, \mathbf{p}$ of length $n$, and I need to compute a vector $\mathbf{\pi}$ defined by

$$\pi_i=\sum_{j=1}^is_j(p_j-p_i)$$

for $i$ from $1$ to $n$.

I suspect this computation could be sped up considerably if it was vectorized, and it seems like I should be able to find $\pi$ by a matrix multiplication, but I can't quite figure out how.

$\endgroup$
1
$\begingroup$

we have: $$ \pi_i=\sum_{j=1}^is_j(p_j-p_i) = \sum_{j=1}^is_j p_j-\left(\sum_{j=1}^is_j\right) p_i= $$ $$= \left(\sum_{j=1}^{i-1}s_jp_j\right)-\left(\sum_{j=1}^{i-1}s_j\right) p_i $$ $$ \begin{bmatrix} \pi_1\\\pi_2\\\pi_3\\\cdot\\\cdot\\\pi_n \end{bmatrix}= \begin{bmatrix} 0&0&0&0&\cdots &0\\ s_1&-s_1&0 &0&\cdots&0\\ s_1&s_2&-(s_1+s_2)&0&\cdots&0\\ s_1&s_2&s_3&-(s_1+s_2+s_3)& \cdots&0\\ \cdots\\ s_1&s_2& \cdots&\cdots&s_{n-1}&-\sum_{j=1}^{i-1}s_j \end{bmatrix} \begin{bmatrix} p_1\\p_2\\p_3\\\cdot\\\cdot\\p_n \end{bmatrix} $$

$\endgroup$
0
$\begingroup$

It depends if the cumulative sum of a vector is a vector command.
Let $$A_i=\sum_{j=1}^is_jp_j\\ B_i=\sum_{j=1}^is_j\\ X_i=A_i-p_iB_i$$ In Matlab, it would be:
A=cumsum(s.*p);
B=cumsum(p);
X=A-p.*B;

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.