A.Rainer
A.Rainer

Reputation: 719

Average across matrices within a structures

I have a structure P with 20 matrices. Each matrix is 53x63x46 double. The names of the matrices are fairly random, for instance S154, S324, S412, etc. Is there any way I can do an average across these matrices without having to type out like this?

M=(P.S154 + P.S324 + P.S412 + ...)/20

Also, does it make sense to use structure for computation like this. According to this post, perhaps it should be converted to cell array.

Upvotes: 2

Views: 139

Answers (2)

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

struct2cell(P)

is a cell array each of whose elements is one of your structure fields (the field names are discarded). Then

cell2mat(struct2cell(P))

is the result of concatenating these matrices along the first axis. You might reasonably ask why it does that rather than, say, making a new axis and giving you a 4-dimensional array, but expecting sensible answers to such questions is asking for frustration. Anyway, unless I'm getting the dimensions muddled,

reshape(cell2mat(struct2cell(P)),[53 20 63 46])))

will then give you roughly the 4-dimensional array you're after, with the "new" axis being (of course!) number 2. So now

mean(reshape(cell2mat(struct2cell(P)),[53 20 63 46]),2)

will compute the mean along that axis. The result will have shape [53 1 63 46], so now you will need to fix up the axes again:

reshape(mean(reshape(cell2mat(struct2cell(P)),[53 20 63 46]),2),[53 63 46])

Upvotes: 1

16per9
16per9

Reputation: 502

If you are using structures, and by your question, you have fieldnames for each matrix.

Therefore, you need to:

1 - use function fieldnames to extract all the matrix names inside your structure. - http://www.mathworks.com/help/matlab/ref/fieldnames.html

2- then you can access it by doing like:

names = fieldnames(P);
matrix1 = P.names{1}

Using a for loop you can then make your calculations pretty fast!

Upvotes: 0

Related Questions