-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcellstd.m
39 lines (32 loc) · 1.17 KB
/
cellstd.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function [sd] = cellstd(x, dim, flag)
% [M] = CELLSTD(X, DIM, FLAG) computes the standard deviation, across all cells in x along
% the dimension dim, normalising by the total number of samples
%
% X should be an linear cell-array of matrices for which the size in at
% least one of the dimensions should be the same for all cells. If flag==1, the mean will
% be subtracted first (default behaviour, but to save time on already demeaned data, it
% can be set to 0).
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellstd');
end
if nargin<2,
scx1 = cellfun('size', x, 1);
scx2 = cellfun('size', x, 2);
if all(scx2==scx2(1)), dim = 2; %let second dimension prevail
elseif all(scx1==scx1(1)), dim = 1;
else error('no dimension to compute mean for');
end
elseif nargin==2,
flag = 1;
end
if flag,
m = cellmean(x, dim);
x = cellvecadd(x, -m);
end
nx = max(nx);
nsmp = cellfun(@nansum, isfinite(x), repmat({dim},1,nx), 'UniformOutput', 0);
ssmp = cellfun(@sumsq, x, repmat({dim},1,nx), 'UniformOutput', 0);
sd = sqrt(nansum(cell2mat(ssmp), dim)./nansum(nsmp));
function [s] = sumsq(x, dim)
s = nansum(x.^2, dim);