Code covered by the BSD License  

Highlights from
meanX

5.0

5.0 | 2 ratings Rate this file 5 Downloads (last 30 days) File Size: 1.17 KB File ID: #34016

meanX

by dberm22

 

30 Nov 2011

meanX calculates the mean (a single value) for any X-dimensional matrix.

| Watch this File

File Information
Description

Just like mean2() calculates the entire mean (a single value) of a 2D matrix, meanX calculates the entire mean for any X-dimensional matrix.

Use meanX() to replace mean2() as it is much more robust (it is not just restricted to 2D matrices). Use it on a 3D, or anyD matrix, and it will work just fine.

This is an extremely simple but incredibly useful macro which I use much more often than I would have initially expected.

Required Products MATLAB
MATLAB release MATLAB 7.13 (2011b)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (9)
30 Nov 2011 Jan Simon

This is faster:
n = numel(A);
for i = 1:ndims(A), A = sum(A); end
A = A / n;

30 Nov 2011 dberm22

Hmm, didn't really take speed into consideration when writing this, as my code worked fast enough for my case. Thanks for the info, though.

30 Nov 2011 dberm22

I will update the code when I get a chance.

30 Nov 2011 Shaun

There are faster ways to do this (as Jan pointed out), but it works well enough.

01 Dec 2011 Xianmin

why not just mean(A(:))?

01 Dec 2011 Sheng Yue

mean(A(:))

01 Dec 2011 dberm22

Yes, that works, too. As one of my professors used to say, there are many ways to skin a cat, but they are all messy.

02 Dec 2011 Jan Simon

@Xianmin: mean(A(:)) is slower than sum(A(:))/numel(A), but both do not use the multi-threaded capabilities of SUM, if it is called for an array.
Another idea to reduce the computing time is sorting the dimensions in descending order:
d = size(A); [dummy, index]=sort(d, 2, 'descend');
for i = index; A = sum(A, i); end
A = A / prod(d);
This reduces the number of elements as fast as possible. E.g. for RAND(4, 100000) this is twice as fast as the original. It is even faster than MEAN(A(:)) and SUM(A(:))/numel(A).

03 Dec 2011 Xianmin

@Jan Simon
Never test it before. But it's good to know that. Thanks!

Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
mean dberm22 30 Nov 2011 15:53:00
mean2 dberm22 30 Nov 2011 15:53:00
mean3 dberm22 30 Nov 2011 15:53:00
meanx dberm22 30 Nov 2011 15:53:00
3d dberm22 30 Nov 2011 15:53:00
4d dberm22 30 Nov 2011 15:53:00
high dberm22 30 Nov 2011 15:53:00
dimensional dberm22 30 Nov 2011 15:53:00
matrix dberm22 30 Nov 2011 15:53:00

Contact us at files@mathworks.com