Finding the mean of all the rows in a field in a struct?

7 views (last 30 days)
Hello Guys,
I have a struct with 1x10 struct with 3 fields so 30 (unknown#1). Each of the (unknown#1) has 300,000 rows and 5 columns, how would i find the mean of each row for each one of the 30 and then put it all into a new struct?
I'm fairly new to matlab and don't know the terminology well. I have spent a few hours attempting to do this and can't seem to find out how.
(Unknown#1) is like a cell in the struct which i don't know what the right terminology is. Thank you very much for any help.

Answers (1)

Guillaume
Guillaume on 8 Nov 2016
It sounds like a structure may not be the ideal type for storing your data. Why is it spread over three different fields if you want to apply the same operation to these fields. Why isn't it all together in a cell array / 3D matrix?
You're going to have to convert your structure into a cell array in order to do what you want anyway, so I suggest leaving it in that form:
%generate demo data. Uses 300 rows instead of 300,000:
s = permute(cell2struct(num2cell(rand(300, 5, 3, 10), [1 2]), {'field1', 'field2', 'field3'}, 3), [1 3 2])
%calculate mean of each element of each field of the structure array:
c = squeeze(struct2cell(s)); %convert into cell array
m = cellfun(@(x) mean(x, 2), c, 'UniformOutput', false)
At this point I would leave it as a cell array. If you really do want a structure:
news = cell2struct(m, fieldnames(s), 1).'

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!