Looping over an array using Fibonacci numbers as a range to calculate the mean
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
DavidSmuts
el 4 de En. de 2022
Comentada: DavidSmuts
el 7 de En. de 2022
Good day,
I have a 2 million x1 double array - doublearray1. I have a second 5x 1 double array containing Fibonacci numbers, more specifically[3,5, 8,13,21] - doublearray2. Note, doublearray2 can change using the Matlab fibonacci function. doublearray2 = fibonacci(n:m).
I would like to loop over doublearray1 and calculate the mean for a range of values in doublearray1, using doublearray2. The mean will be stored in doublearray3
The loop will run as follows:
doublearray3(1-5,1) = mean(doublearray1(1:1+3)) then mean(doublearray1(4:4+5)) then mean(doublearray1(9:9+5)) then mean(doublearray1(14:14+13)) then mean(doublearray1(27:27+21))
doublearray3(5-10,1) = mean(doublearray1(48: 48+3)) then mean(doublearray1(51:51+5)) then mean(doublearray1(56:56+8)) then mean(doublearray1(64:64+13)) then mean(doublearray1(77:77+21))
... doublearray3(2000000, 1)
I would appreciate any help with the code for this.
Thanks
3 comentarios
Respuesta aceptada
Jan
el 5 de En. de 2022
Editada: Jan
el 5 de En. de 2022
What should happen with the last chunk, if you cannot find enough elements in the input data?
Should the 1st term really be: mean(doublearray1(1:1+3)), so it is the mean over 4 elements, not 3?
The element 4 is included in the first mean value and in the second one also?
In your description the element doublearray3(5) is defined as last element of the first block and first element of the second block again: "doublearray3(1-5,1)=..." and "doublearray3(5-10,1)". Is the wanted?
Here a code, which calculates the mean over 3, 5, 8, ... elements without overlap:
pool = [3, 5, 8, 13, 21];
data = rand(2e6, 1);
npool = numel(pool);
out = zeros(numel(data), 1); % Pre-allocate too much memory
i1 = 1; % Start of current chunk
ndata = numel(data);
k = 0;
while i1 <= ndata
n = pool(rem(k, npool) + 1); % Get next element from pool
i2 = min(i1 + n - 1, ndata); % End of current chunk
k = k + 1; % Index of output
out(k) = sum(data(i1:i2)) / (i2 - i1 + 1);
i1 = i2 + 1; % Start is current End + 1
end
out = out(1:k); % Crop unneded elements
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!