Writing a Matlab script to implement a changing sum

52 Views Asked by At

I am trying to implement this computation in Matlab, but I don't know how.

I want to compute the following:

$$p(k,j) = \frac{\sum\limits_{i=j+1}^{k} x_{i-1}}{\sum\limits_{i=j+1}^{k}(y_{i-1} - y_i)}$$ where $j = 0,\ldots,k-1$. For example for $k = 2$, $j = 0,1$. Thus,

$$ p(2,0) = \frac{\sum\limits_{i=1}^{2}x_{i-1}z_{i-1}}{\sum\limits_{i=1}^2 (y_{i-1}-y_i)} \quad \text{and} \quad p(2,1) = \frac{\sum\limits_{i=2}^{2}x_{i-1}z_{i-1}}{\sum\limits_{i=2}^2 (y_{i-1}-y_i)} $$

For $k=3$, $j=0,1,2$ and $$p(3,0) = \frac{\sum\limits_{i=1}^{3}x_{i-1}z_{i-1}}{\sum\limits_{i=1}^3 (y_{i-1}-y_i)}\,,p(3,1) =\frac{\sum\limits_{i=2}^{3}x_{i-1}z_{i-1}}{\sum\limits_{i=2}^3 (y_{i-1}-y_i)} \,, p(3,2) =\frac{\sum\limits_{i=3}^{3}x_{i-1}z_{i-1}}{\sum\limits_{i=3}^3 (y_{i-1}-y_i)} ~.$$

I have the values of $x$ and $y$ but I only have the initial value of $z$, $z_0$. The next value of $z$ is found iteratively: $$z_i = z_{i-1} - 1/p(k,j). $$

1

There are 1 best solutions below

3
On BEST ANSWER

Matlab has one-based array indexing: x(1), x(2) and so on. You need to take it into account. If p(k,j) is two-dimensional array, then you need to change indexing too.

Let: x_(i+1) = x(i), y_(i+1) = y(i), z_(i+1) = z(i), p_(k+1,j+1) = p(k,j)

So, $p(k,j)$ is calulated, using element-wise multiplication .*, difference and vector sum operations, with this code:

p_(k+1,j+1) = sum(x_(j+1:k).*z_(j+1:k))/sum(y_(j+1:k)-y_(j+2:k+1))

One more hint, MATLAB has built-in function diff, calculating difference of neighbour elements. diff(X), for a vector X, is [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)]. So we can write:

p_(k+1,j+1) = sum(x_(j+1:k).*z_(j+1:k))/sum(-diff(y_(j+1:k+1)))