How can I do the rolling sum of 5 elements for each column? I have a dataset like this, and would be greatful, someone can help me to write a code for rolling sum of 5 elements of each column.

1 visualizzazione (ultimi 30 giorni)
da =
39.00 34.00 40.00 38.00 151.00
47.00 33.00 35.00 48.00 163.00
42.00 46.00 43.00 51.00 182.00
40.00 30.00 37.00 39.00 146.00
39.00 30.00 42.00 30.00 141.00
40.00 29.00 45.00 35.00 149.00
25.00 35.00 47.00 30.00 137.00
36.00 28.00 37.00 28.00 129.00
24.00 37.00 37.00 34.00 132.00

Risposta accettata

Stephen23
Stephen23 il 9 Mar 2016
Modificato: Stephen23 il 9 Mar 2016
Use conv2:
>> X = conv2(da,ones(5,1))
Note that there are several options for selecting what to do with the sums at the edges: you need to read the documentation carefully and pick the one that suits your needs best. For example the option 'valid' only keeps the values for which five values are summed, thus excluding the edges values:
>> X = conv2(da,ones(5,1),'valid')
X =
207 173 197 206 783
208 168 202 203 781
186 170 214 185 755
180 152 208 162 702
164 159 208 157 688
If you want the sums starting from the first row but keeping only as many rows as da has, then try using the option 'full':
>> X = conv2(da,ones(5,1),'full');
>> X(1:size(da,1),:)
ans =
39 34 40 38 151
86 67 75 86 314
128 113 118 137 496
168 143 155 176 642
207 173 197 206 783
208 168 202 203 781
186 170 214 185 755
180 152 208 162 702
164 159 208 157 688
  6 Commenti
Stephen23
Stephen23 il 10 Mar 2016
Modificato: Stephen23 il 10 Mar 2016
Obviously if you try to access an element of a matrix that does not exist then this is an error.
The solution depends on you. You have not given enough information for me to know what you need, or what exactly you are plotting. If you actually show us your code then we know what you are doing.
The different conv2 options give different size output matrices. I do not know what size you want because you have not told us what size you want the output to be.
I am going to make a guess that you want the output to be the same size as the input da. These will work, but keep in mind they give different results and only you know what results you need. Whatever results you need don't forget check them by hand!
X =conv2(da,ones(5,1),'same') % X same size as da
or
X = conv2(da,ones(5,1),'full');
X = X(1:size(da,1),:) % shortened X to same size as da
Possibly you want to shorten da to be the same length as the valid output:
X = conv2(da,ones(5,1),'valid');
db = da(1:size(X,1),:) % shortened da to same size as X

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by