" Sumif" type Aggregatio​n/Consolid​ation along one dimesion of a 3d matrix

4 views (last 30 days)
This is my first project using Matlab so please be gentle. I usually just poke around in Excel.
I have a 3D Matrix, say 3 x 3 x 5
A = [5 7 8; 0 1 9; 4 3 6];
A(:,:,2) = [1 0 11; 3 5 6; 9 8 7]
A(:,:,3) = [5 0 2; 1 5 6; 9 5 7]
A(:,:,4) = [1 0 4; 3 5 13; 9 8 7]
A(:,:,5) = [5 0 2; 1 5 6; 9 5 7]
The first two dimensions (M x N) represent values on a equally spaced mesh (Spatial mesh), the co-ordinates for these points are held using the meshgrid function. The third dimension is effectively the time series of these values.
Example: a equally spaced grid of microphones measures decibels across equally spaced time increments while people singing with variable volume walk amongst the grid. (hope that makes sense.) Each persons “sound level contribution (dB)” is measured at each “microphone” for each timestep (2D propagation only). The number of people in the system changes over time. I need to find the total sound level at each microphone for each time step by summing the mesh grid of each person in the system for that time step.
What I need to do is “aggregate” or “consolidate” along this third dimension matching discrete values in another vector X.
X=[1 2 3 2 1]
Result = A = [10 7 10; 1 6 15; 13 8 13];
A(:,:,2) = [2 0 15; 6 10 19; 18 16 14]
A(:,:,3) = [5 0 2; 1 5 6; 9 5 7]
It is effectively a “SUMIF” function in excel but across the “pages” of a 3D matrix.
Here’s a 2D example:
>> X=[1 2 3 2 1 3 2]; Y=[2 1 5 1 3 4 6];
SS = max(X);
for i = 1:SS
agTimeStepLWA (i) = sum(Y(X == i));
end
agTimeStepLWA =
5
8
9
For my project, the first two dimensions are in the order of 10-100 and the third dimension is in the order of 100 000 to several million. Here’s some links I looked at but couldn’t gleam anything from.
Thanks

Answers (1)

Teja Muppirala
Teja Muppirala on 7 May 2011
Scaling your 1-D Version up to a 3-D one:
Asum = zeros([size(A(:,:,1)) max(X)]);
for n = 1:max(X)
Asum(:,:,n) = sum(A(:,:,X == n),3);
end
There may be other vectorized (ACCUMARRAY-like) of ways of doing it, but I think a loop might be more memory efficient and reasonably fast, particularly if max(X) is not that big. Not sure though. Maybe someone will come by with a better idea.

Categories

Find more on Language Fundamentals 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!