0

私の前の質問の一般化では、セル要素(配列自体であり、配列のままである)の加重平均をどのように実行できますか?


次のようにgnoviceの回答を変更することから始めます。

dim = ndims(c{1});          %# Get the number of dimensions for your arrays
M = cat(dim+1,c{:});        %# Convert to a (dim+1)-dimensional matrix
meanArray = sum(M.*weigth,dim+1)./sum(weigth,dim+1);  %# Get the weighted mean across arrays

その前にweight、正しい形状であることを確認してください。私が対処する必要があると思う3つのケースは次のとおりです。

  1. weight = 1 (または任意の定数) => 通常の平均値を返す
  2. numel(weight) == length(c) => weight は cell-element c{n} ごと (ただし、固定 n の各配列要素については等しい)
  3. numel(weight) == numel(cell2mat(c)) => 各配列要素には独自の重みがあります...

M.*weightケース 1 は簡単で、ケース 3 が発生する可能性は低いので、現時点ではケース 2 に興味があります:上記の合計で正しい次元を持つように、重みを配列に変換するにはどうすればよいですか? もちろん、加重平均を取得する別の方法を示す回答も高く評価されます。


編集実際、重みが c と同じ構造を持つ場合、ケース 3 はケース 1 よりもさらに自明です(なんとトートロジー、申し訳ありません)。

ケース2の意味の例を次に示します。

c = { [1 2 3; 1 2 3], [4 8 3; 4 2 6] };
weight = [ 2, 1 ];

戻るべき

meanArray = [ 2 4 3; 2 2 4 ]

(たとえば、最初の要素の場合 (2*1 + 1*4)/(2+1) = 2)

4

1 に答える 1

1

REPMATに慣れた後、私の解決策は次のとおりです。

function meanArray = cellMean(c, weight)
% meanArray = cellMean(c, [weight=1])
% mean over the elements of a cell c, keeping matrix structures of cell
% elements etc. Use weight if given.

% based on http://stackoverflow.com/q/5197692/321973, courtesy of gnovice
% (http://stackoverflow.com/users/52738/gnovice)
% extended to weighted averaging by Tobias Kienzler
% (see also http://stackoverflow.com/q/5231406/321973)

dim = ndims(c{1});          %# Get the number of dimensions for your arrays
if ~exist('weight', 'var') || isempty(weight); weight = 1; end;
eins = ones(size(c{1})); % that is german for "one", creative, I know...
if ~iscell(weight)
    % ignore length if all elements are equal, this is case 1
    if isequal(weight./max(weight(:)), ones(size(weight)))
        weight = repmat(eins, [size(eins)>0 length(c)]);
    elseif isequal(numel(weight), length(c)) % case 2: per cell-array weigth
        weight = repmat(shiftdim(weight, -3), [size(eins) 1]);
    else
        error(['Weird weight dimensions: ' num2str(size(weight))]);
    end
else % case 3, insert some dimension check here if you want
    weight = cat(dim+1,weight{:});
end;

M = cat(dim+1,c{:});        %# Convert to a (dim+1)-dimensional matrix
sumc = sum(M.*weight,dim+1);
sumw = sum(weight,dim+1);
meanArray = sumc./sumw;  %# Get the weighted mean across arrays
于 2011-03-09T10:31:03.167 に答える