Add up a certain number of consecutive values followed by the next values in a row

4 vues (au cours des 30 derniers jours)
Dennis Annutsch
Dennis Annutsch le 17 Août 2021
Commenté : Dennis Annutsch le 17 Août 2021
Good morning,
I am looking for a function that can do the following:
E.g.
A = [1 3 4 0 -1 6]
Result = 4 4 5
Always added up two values from the beginning - then the next two values - and so on.
It would be nice to have the option to say please always add up 3 values, so that the result would be: Result = 8 5
Thanks for your help!
Dennis

Réponses (2)

Wan Ji
Wan Ji le 17 Août 2021
I'll write for you!
function a = everynsum(arr, n)
p = length(arr);
a = sum(reshape(arr,n,p/n)); % in case mod(p,n)=0
end
  2 commentaires
Wan Ji
Wan Ji le 17 Août 2021
By movsum you can do:
A = [1 3 4 0 -1 6];
n = 2; % every 2 sum
B = movsum(A,n);
Result = B(n:n:end)
The result is
Result =
4 4 5
Dennis Annutsch
Dennis Annutsch le 17 Août 2021
Thank you very much!! This works exactly as I imagined. I wish you all the best!

Connectez-vous pour commenter.


Awais Saeed
Awais Saeed le 17 Août 2021
clc;clear all;close all
A = [1 3 4 0 -1 6];
n = 2; % sum every n elements
jj = 0;
simdone = true; % to keep while loop running
while (simdone)
jj = jj + 1;
if (size(A,2) == n)
result(jj) = sum(A(1:n));
break % break while loop
end
result(jj) = sum(A(1:n));
A(1:n) = []; % deleting summed elements
end

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by