Sum of array items into another array

조회 수: 2(최근 30일)
np 2016년 6월 22일
댓글: Shameer Parmar 2016년 6월 24일
I need to find the sum of items within each of the 360 arrays and then make another array with just the sums.
  댓글 수: 8
Kirby Fears
Kirby Fears 2016년 6월 22일
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?

댓글을 달려면 로그인하십시오.

채택된 답변

Kirby Fears
Kirby Fears 2016년 6월 22일
Assuming data is a struct with fields speed1, speed2, etc.
sumArray = structfun(@sum,data);

추가 답변(2개)

Guillaume 2016년 6월 23일
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
Shameer Parmar 2016년 6월 23일
for i=1:length(fields(data))
s(i) = sum(eval(['data.speed',num2str(i)]));
  댓글 수: 6
Shameer Parmar
Shameer Parmar 2016년 6월 24일
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)]));

댓글을 달려면 로그인하십시오.


Community Treasure Hunt

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

Start Hunting!

Translated by