3

サイズ<20x1x19>のセル配列Cがあり、それぞれ19個の要素にサイズ(80x90)の20個の行列のセットが含まれています。各20個の行列の平均を計算し、結果を行列Mに格納するにはどうすればよいですか。最終的に、セル配列行列の平均を含むサイズ80x90x19の行列が作成されます。

例えば:

M(:、:、1)は、C(:、:、1);の要素の平均を持ちます。

M(:、:、2)は、C(:、:、2)の要素の平均を持ちます

等々。

4

2 に答える 2

4

配列を少し操作するだけで、ループを回避できます。cell 配列の次元を変更して、cell2mat結果が 80 x 90 x 19 x 20 の配列になるようにすることができます。その後は、次元 #4 に沿って平均を取るだけです。

%# C is a 20x1x19 cell array containing 80x90 numeric arrays

%# turn C into 1x1x19x20, swapping the first and fourth dimension
C = permute(C,[4 2 3 1]);

%# turn C into a numeric array of size 80-by-90-by-19-by-20
M = cell2mat(C);

%# average the 20 "slices" to get a 80-by-90-by-19 array
M = mean(M,4);
于 2012-10-10T13:02:42.967 に答える
2

私があなたを正しく理解していると仮定すると、あなたは次の方法であなたが望むことをすることができます(コメントは私が行うことを段階的に説明しています):

% allocate space for the output
R = zeros(80, 90, 19);

% iterate over all 19 sets
for i=1:19
    % extract ith set of 20 matrices to a separate cell
    icell = {C{:,1,i}};

    % concatenate all 20 matrices and reshape the result
    % so that one matrix is kept in one column of A 
    % as a vector of size 80*90
    A = reshape([icell{:}], 80*90, 20);

    % sum all 20 matrices and calculate the mean
    % the result is a vector of size 80*90
    A = sum(A, 2)/20;

    % reshape A into a matrix of size 80*90 
    % and save to the result matrix
    R(:,:,i) = reshape(A, 80, 90);    
end

抽出をスキップしてicell、20個の行列のi番目のセットを直接連結することができます

A = reshape([C{:,1,i}], 80*90, 20);

ここでは、わかりやすくするためにのみ行いました。

arrayfun上記の手順は、次の呼び出しでより簡単に表現できます(ただし、間違いなくはるかに不可解です!) 。

F = @(i)(reshape(sum(reshape([C{:,1,i}], 80*90, 20), 2)/20, 80, 90));
R = arrayfun(F, 1:19, 'uniform', false);
R = reshape([R2{:}], 80, 90, 19);

匿名関数Fは、基本的にループを1回繰り返します。arrayfunこれは、行列のセットごとに1回、によって19回呼び出されます。私はあなたがループに固執することをお勧めします。

于 2012-10-10T11:10:26.663 に答える