1
votes

I have a 221 x 24 cell array, S. Within each array is another array consisting of several different fields (let's just say A, B, C, and D), whereby each field (A, B, C, D) are a 50 x 50 array. I want to sum only the A's, B's, C's, and D's within each column of array S. For example:

S{1,1}.A + S{2,1}.A + ... + S{23,1}.A ...

S{1,2}.B + S{2,2}.B + ... + S{153,2}.B ...

S{111,3}.C + S{117,3}.C + ... + S{230,3}.C ...

What is the simplest way to do this? I know there is a function to sum if there are no fields within the structure (e.g., sum([S{:}]) ), but I only want the specific fields in each summed. Any thoughts?

1
Can you provide a sample of what you have? Is there only one field per cell? - Sardar Usama
Please bring an example from all field. - PyMatFlow
S{3,1} could contain: S{3,1}.A, S{3,1}.B, S{3,1}.C, ..., S{3,1}.L Where A, B, C, D ... L are all 50 x 50 arrays. I want to sum S{3,1}.A with S{4,1}.A, S{5,1}.A, ..., S{n,1}.A and then sum S{3,1}.B with S{4,1}.B, S{5,1}.B, ..., S{n,1}.B The arrays of A, B, C, D, ..., L are a simple 50x50 array of numbers. I can do: for m = 50 for n = 50 S{3,1}.A(m,n) + S{4,1}.A(m,n) + ... But that thats long and would like to try and automate it in a nicer code. - Miss_Orchid

1 Answers

0
votes

There is likely more "MATLABy" way of avoiding loops and making this even simpler, but this loop should be reasonably straightforward:

FN = fieldnames(S{1});
for i = 1 : size(S, 1)
   sumStruct{i} = 0;
   for j = 1 : size(S, 2)
      sumStruct{i} = sumStruct{i} + S{i,j}.(FN{j});
   end
end

This assumes you want sum of all S{1...N, 1}.A, S{1...N, 2}.B and so on, as it appears in the question. If you want S{1...N, 1}.B too you need 3rd loop and 2 indices for sumStruct - it should be relatively straightforward to implement.