How to calculate the mean for specific rows in a cell using cellfun

A cell A{1}=a1 A{2}=a2 ... A{5}=a5
a1=[1 1 1 1 ; 2 2 2 2; 3 3 3 3; 4 4 4 4;]
a2 =
[ 2 2 2 2;
3 3 3 3;
4 4 4 4;
5 5 5 5;]
...
I want to get the two mean values for the first two rows and the last two rows seperately. Can I realize this using the following function instead of a loop? cellfun(@nanmean,A, 'UniformOutput',false);

Antworten (3)

Azzi Abdelmalek
Azzi Abdelmalek am 8 Dez. 2012
Bearbeitet: Azzi Abdelmalek am 8 Dez. 2012
A={rand(4);rand(4);rand(4);rand(4);rand(4);rand(4)}
n=numel(A)
c=arrayfun(@(x) mean(mean(A{x})),[1 2 n-1 n],'un',0)

3 Kommentare

Hi Azzi,
Thanks for your reply. But i don't have the A{x} with the row nr. = col nr. . The size for each A{x} is 10*4000.
So I run your code and can't get the idea result that I want, which should be Mean(first 5 rows in A{x}) and Mean(last 5 rows in A{x}).
Can you help me further about this?
Thanks
I don't store in 3 D due to the memory problem.
Skirt, in your question you said 2 first rows and two last rows, From your post, A is a cell array of n elements, each element is a matrix. Can you explain clearly what is the expected result (look at my example)
If you wat first 5 and last 5, just adapt the above code
A={rand(4);rand(4);rand(4);rand(4);rand(4);rand(4)}
n=numel(A)
nr=5
c=arrayfun(@(x) mean(mean(A{x})),[1:nr n-nr+1:n],'un',0)

Melden Sie sich an, um zu kommentieren.

Matt J
Matt J am 8 Dez. 2012
Can I realize this using the following function instead of a loop? cellfun(@nanmean,A, 'UniformOutput',false);
You can, but there will be no advantage in performance over the for loop.
Incidentally, if all the A{i} are the same size, as in your example, it's puzzling that you wouldn't maintain them as a 3D array A(:,:,i). Then you could just do
nanmean(A([1,end],:,:),2)
José-Luis
José-Luis am 9 Dez. 2012
Bearbeitet: José-Luis am 9 Dez. 2012
It is not really clear how you want to split your data, so I added two variables, rowsFromStart and rowsFromEnd so you can specify it yourself. It is also not very clear if you want one mean for each row or the mean of all rows. Finally, a loop would probably be faster.
A={rand(10,100);rand(10,100);rand(10,100);rand(10,100);rand(10,100);rand(10,100)}
rowsFromStart = 5;
rowsFromEnd = 5;
c=cellfun(@(x) [mean(mean(x(1:rowsFromStart-1,:),2));mean(mean(x(end:end-rowsFromEnd+1,:),2))],A,'un',0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 8 Dez. 2012

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by