Weighted mean of a 3D matrix
2 views (last 30 days)
Show older comments
Hello
I have a 3D matrix with dimensions 2496x10x13857, representing velocities. The dimensions are time, depth and node ID, repectively. I am trying to calucalte the depth weighted average of this matrix. I have a 10x1 matrix with values ranging from 0 to -1 which are the sigma depths. I have been trying out a number of different ways of doing this but I keep getting errors. My script so far:
u=modS.u;
u_new=sum(u.*(siglay'*-1),3)./sum(siglay'*-1,1);
The above calculates the mean but gives a 2496x10 matrix, which is not what I want. I would like the final matrix to be 2496x13857. I have tried to use permute to see if that works but it doesn't. Does anyone have any suggestions as to how I could go about this?
Thanks in advance :)
0 Comments
Accepted Answer
the cyclist
on 8 Sep 2017
Edited: the cyclist
on 8 Sep 2017
% Define array with some pretend data
S = rand(2496,10,13857);
D = rand(10,1);
% Take the weighted mean:
% (1) Reorient D to align with 2nd dimension
% (2) Take weighted mean along 2nd dimension
% (3) Reshape again to get rid of singleton 2nd dimension
wS = reshape(mean(S.*reshape(D,[1,10,1]),2),[2496,13857]);
You could have done similar things using permute instead of reshape.
Also, you could have used "squeeze" in step 3, but sometimes that command has unintended consequences, if some other dimension has length 1 unexpectedly.
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices 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!