Clear Filters
Clear Filters

How to sum pages of a multidimensional array inside a structure array?

4 views (last 30 days)
Hi,
I have a structure array "A" with one field "a". The field "a" consists from 200 muldidimensional arrays of equal size 11x11x5. let's call the elements within field "a" in the following way: "a1", "a2", "a3" and so on up to "a200". For element "a1" I have to sum all pages from 1 to 5 and at the end I should have a matrix 11x11. The same summation I should do for every element within the field "a" from element "a1" to element "a200". At the end I should get a struct array "A" with field "a". Field "a" will now have 200 elements "a1" to "a200" and these all will be matrices 11x11.
I have tried to do the sum in this way
for p = 1:200
A(p).a_sum = sum(structfun(@sum, A(p).a(:,:,3)));
end
But I get this error: Error using structfun Inputs to STRUCTFUN must be scalar structures.
Can you help me how to write the sum in a proper way?
Thanks!

Accepted Answer

Jan
Jan on 13 Dec 2016
Edited: Jan on 13 Dec 2016
"A(p).a(:,:,3)" is a matrix, therefore you cannot provide it as input to structfun. You could use structfun for the summation:
structfun(@x sum(x, 3), A)
but this is easier and most likely faster:
for p = 1:200
A(p).a_sum = sum(A(p).a, 3);
end

More Answers (1)

Jos (10584)
Jos (10584) on 13 Dec 2016
Given the description, I assume you have an array of structures A. Each element of this array has a field a which holds a 3D (11x11x5) array. For each of the the 200 elements of the structure array A you want to sum this field across the 3rd dimension:
% create some data
% 10 element structure array "A" with a field "a" holding a random 3x3x2 array
[A(1:10).a] = deal(rand(3,3,2)) % smaller examples work better
myfun = @(k) sum(A(k).a, 3) % a function to sum across the 3d dimension of field a
C = arrayfun(myfun, 1:numel(A), 'un', 0) % apply myfun to all elements of A
[B(1:numel(A)).a_sum] = deal(C{:}) % distribute over elements of a new structure array

Categories

Find more on Data Types 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!