# How can I create a vector that shows the sum of the 60 values before each value of another vector?

4 vues (au cours des 30 derniers jours)
Philippe Corner le 13 Jan 2017
Commenté : Walter Roberson le 13 Jan 2017
If a have this vector --> x=[0:1:1000] how can i create a vector of length 1000 too.. that is: first value 0, second 0+1.. value #59 from 0 to 59 and when the value is greater than 60 it shows the sum of the 60 values before for example the entry 100 should be from 40 to 100 etc..
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Walter Roberson le 13 Jan 2017
"60 values before" implies that 60 values are to be added. 40 to 100 is 61 values.

Connectez-vous pour commenter.

### Réponses (3)

Walter Roberson le 13 Jan 2017
Or you can cumsum() and subtract the value 60-ish earlier in the cumsum
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Walter Roberson le 13 Jan 2017
t = cumsum(zeros(1,60),x);
t(61:end) - t(1:end-60)

Connectez-vous pour commenter.

Star Strider le 13 Jan 2017
I’m not certain a vector is possible, but a matrix approach could be.
Consider the rows of ‘out’:
N = 5; % RowLength (Use: 60)
L = 10; % Vector Length (Use: 1000)
out = hankel(1:N, N:L);
out(2:end,:) = cumsum(out(2:end,:),2);
I used the example with a short vector to illustrate the approach. Experiment to get the result you want.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

Image Analyst le 13 Jan 2017
Here's a way to do it in one line of code with conv().
out = conv(x, [zeros(1,59), ones(1,60)], 'same')
To prove it, here's a full demo where I compare that method to a simple intuitive for loop to prove that it's the same.
x=[0:1:1000]
kernel = [zeros(1,59), ones(1,60)]
out = conv(x, kernel, 'same')
% Compare with for loop method:
for k = 1 : length(x)
i2 = k;
i1 = max(1, i2 - 59);
outf(k) = sum(x(i1:i2));
end
diffs = outf - out
maxDiff = max(diffs) % Should be 0
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Logical dans Help Center et File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by