Sum of array items into another array
2 views (last 30 days)
Show older comments
np on 22 Jun 2016
Commented: Shameer Parmar on 24 Jun 2016
I need to find the sum of items within each of the 360 arrays and then make another array with just the sums.
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?
Assuming data is a struct with fields speed1, speed2, etc.
sumArray = structfun(@sum,data);
More Answers (2)
Guillaume on 23 Jun 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)));
Shameer Parmar on 23 Jun 2016
s(i) = sum(eval(['data.speed',num2str(i)]));
Shameer Parmar on 24 Jun 2016
I guess your length of fields(data) is more that 360, that why..
If yes, you can apply one more filter like..
s(i) = sum(data.(['speed',num2str(i)]));
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!