Taking the mean of rows in a structure array

13 views (last 30 days)
Hi everyone,
I am stumped on this and am guessing that someone might know an easy way to do this, so thanks in advance for any help you might be able to offer.
I have a 1x300 struct object. Each element of the struct is a 3453x1 double array. I would like to take a mean of the values in the double arrays row by row. So basically, something like this (I know this code doesn't work):
for j=1:3453
nmfinal(j,1)=mean(nm.data(j,1))
end
This throws up the error "Field reference for multiple structure elements that is followed by more reference blocks is an error." which I have spent a good deal of time Googling but am not really finding an example similar enough to mine to be really useful. Likewise, if I try to use something like
nm(:).data(j,1)
I get the error "Scalar index required for this type of multi-level indexing."
How might I go about accessing all the data(j,1) doubles to compute a mean? I guess I can resort to looping through the struct but was hoping there might be an easier way...
Best Wishes, J. Nathan Scott

Answers (2)

Hugo
Hugo on 7 Jul 2014
You can do the following:
nmfinal=mean(cell2mat(squeeze(struct2cell(nm.data))'))';
You might need to take some precautions though. The final result depends on how you arrange the data, that is, if the data structure is a row vector or a column vector, and if the data inside each element of the data structure is a column vector or a row vector. Notice that I have used a transpose in the middle and the end of the expression so that it works with the arrangement you mentioned in your question and gives you a column vector as a result.
Hope this helps.

Jos (10584)
Jos (10584) on 7 Jul 2014
I assume NM is your 300 element structure array. with NM(k).data holding the 3453 data points of the kith element of the structure
nmfinal = arrayfun(@(k) mean(NM(k).data), 1:numel(NM))

Categories

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