# Sum of array items into another array

1 vue (au cours des 30 derniers jours)
np le 22 Juin 2016
Commenté : Shameer Parmar le 24 Juin 2016
I need to find the sum of items within each of the 360 arrays and then make another array with just the sums.
##### 8 commentairesAfficher 6 commentaires plus anciensMasquer 6 commentaires plus anciens
np le 22 Juin 2016
the speed1 speed2 are just the names of the arrays that are there
the values inside of them are numeric
Kirby Fears le 22 Juin 2016
I understand that the values inside of speed1 and speed2 are numeric, but you wrote your example as "data.speed1". So are speed1 and speed2 contained in a workspace variable called data or not?

Connectez-vous pour commenter.

### Réponse acceptée

Kirby Fears le 22 Juin 2016
Assuming data is a struct with fields speed1, speed2, etc.
sumArray = structfun(@sum,data);
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Plus de réponses (2)

Guillaume le 23 Juin 2016
If your structure has fields other than the speed fields, you can loop over a hardcoded number of speed fields:
numspeed = 360;
speedsum = zeros(numspeed, 1);
for speedidx = 1:numspeed
speedsum(speedidx) = sum(data.(sprintf('speed%d', speedidx)));
end
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

Shameer Parmar le 23 Juin 2016
for i=1:length(fields(data))
s(i) = sum(eval(['data.speed',num2str(i)]));
end
##### 6 commentairesAfficher 4 commentaires plus anciensMasquer 4 commentaires plus anciens
Guillaume le 23 Juin 2016
1) Use fieldnames instead of fields. That won't solve the immediate problem as they both provide the same result, but fields is not supported whereas fieldnames is.
2) You get this error because your data has fields other than the 360 speed fields.
Shameer Parmar le 24 Juin 2016
Hello np..
I guess your length of fields(data) is more that 360, that why..
If yes, you can apply one more filter like..
for i=1:length(fields(data))
if i<=360
s(i) = sum(data.(['speed',num2str(i)]));
end
end

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Structures 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