Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using cellfun for mean of cell

Tags:

matlab

I have a cell:

BED4{6,4,4}=[];

eg. BED4{1}{1}{1}
ans = 

    [8x1 double]    [8x1 double]    [8x2 double]    [8x1 double]

I would like to calculate the mean as if it were via a for loop along the red arrow:

enter image description here

So far I'm having to do this...

figure('color',[1 1 1])
titles={'Direct care','Housekeeping','Mealtimes','Medication rounds','Miscellaneous care','Personal care'};

for care=1:6
    subplot(3,2,care)
    clear a m e pci1 pci2 gn
for position=1:4
    for patient=1:4
a(:,:,position,patient,care)=cell2mat(BED4{care}{position}{patient});
    end
end

m=mean(mean(a(:,1,:,:,care),4),3);
e=mean(mean(a(:,2,:,:,care),4),3);
pci1=mean(mean(a(:,3,:,:,care),4),3);
pci2=mean(mean(a(:,4,:,:,care),4),3);
gn=a(:,5,1,1,care);
if care==1
    b={m,e,pci1,pci2,gn}; %store for posterity
end

h=errorbar(gn,m,e,'sr');

set(h,'linestyle','--','LineWidth',2,...
                'MarkerEdgeColor','k',...
                'MarkerFaceColor','white',...
               'MarkerSize',5);
ylabel('Relative Risk ');
xlabel('Patient contact count');
title(titles{ii})
set(gca,'xtick',0:2:8)
axis([-2 8 0 1])
end

which gives:

enter image description here

like image 888
HCAI Avatar asked May 16 '13 09:05

HCAI


1 Answers

It's easier if you reshape your data to isolate the first dimension (care):

C = reshape(BED4, size(BED4, 1), 1);

Each row corresponds to a different value of care. Let's stack the content of the cells in each row as a 3-D matrix and obtain the desired mean values:

res = cell(size(C, 1), 1);               %// Preallocate memory
for care = 1:size(C, 1)
    X = vertcat(C{care, :});             %// Obtain content from row
    func = @(k)mean(cat(3, X{:, k}), 3); %// Stacks content and obtains mean
    res{care} = arrayfun(func, 1:size(X, 2), 'UniformOutput', 0);
end

The resulting cell array res should contain all the desired mean values.

like image 179
Eitan T Avatar answered Oct 07 '22 02:10

Eitan T