结构线的平均值

Mean of structure's line

我有一个类似

的结构
struct =
Fields   Subject1          Subject2        Subject3      Subject4
    1 30000x1 double    30000x1 double  30000x1 double  30000x1 double
    2 30000x1 double    30000x1 double  30000x1 double  30000x1 double
    3 30000x1 double    30000x1 double  30000x1 double  30000x1 double
    4 30000x1 double    30000x1 double  30000x1 double  30000x1 double

其中 1、2、3 和 4 是条件

我想计算每个条件的平均值,所以对于结构的每条线。

我试过:

for i = 1:length(struct)
mean_condition(i) = mean([strut(i)]);
end

但我得到这个错误

Error using sum
Invalid data type. First argument must be numeric or logical.

Error in mean (line 117)
        y = sum(x, dim, flag)/size(x,dim);

我该如何解决?

虽然 structfun allows you to perform an operation over the fields of a structure, it only works with scalar arrays. Because you have a structure array, you'll need to use an explicit loop or an implicit arrayfun 循环。

以后者为例:

condition(1).subject1 = 1:10;
condition(1).subject2 = 1:20;
condition(2).subject1 = 1:30;
condition(2).subject2 = 1:40;

results = arrayfun(@(x)mean(structfun(@mean, x)), condition).';

这给了我们:

results =

     8
    18

我们可以验证的是:

>> [mean([mean(condition(1).subject1), mean(condition(1).subject2)]); mean([mean(condition(2).subject1), mean(condition(2).subject2)])]

ans =

   8
   18

根据 MA​​TLAB 版本,由于额外的函数调用开销,*fun 函数可能比显式循环慢。旧版本的 MATLAB 肯定是这种情况,但是引擎的改进已经开始使它们的性能保持一致。

为了完整起见,一个明确的循环版本:

results = zeros(numel(condition, 1));
for ii = 1:numel(condition)
    tmpnames = fieldnames(condition(ii));
    tmpmeans = zeros(numel(tmpnames, 1));
    for jj = 1:numel(tmpnames)
        tmpmeans(jj) = mean(condition(ii).(tmpnames{jj}));
    end
    results(ii) = mean(tmpmeans);
end

由于数组中所有结构的字段大小相同,您可以非常轻松地执行此计算,如下所示:

s = struct();
s_len = 4;

for i = 1:s_len
    s(i).Subject1 = repmat(i,30,1);
    s(i).Subject2 = repmat(i,30,1);
    s(i).Subject3 = repmat(i,30,1);
    s(i).Subject4 = repmat(i,30,1);
end

m = reshape(mean(cell2mat(struct2cell(s))),s_len,1);

然后变量 m 是双精度值的行向量,其中每一行包含相应条件的平均值:

m =
     1 % mean of condition 1
     2 % mean of condition 2
     3 % mean of condition 3
     4 % mean of condition 4