2

我想将矩阵按列拆分为 3 段并对其进行计算(mean())。有没有办法在没有for循环的情况下获得这个,就像我在这个提供的示例中所做的那样?

M = [2 4 9; 50 50 200; 30 0 0];
M = [M 10*M]
N = length(M);
seg = 3 % split in lets say 3 parts
segLen = round(N/seg)
segBeg = (((1:seg)-1) * segLen)+1  % start indices
segEnd = segBeg + segLen -1        % end indices

for i = 1: length(segBeg)
    mean(M(:,segBeg(i):segEnd(i)),2)
end

谢谢!

4

3 回答 3

3

跳出框框思考:使用第三维:

r=reshape(M,size(M,1),segLen,[])
squeeze(mean(r,2))

第一行产生一个 3d 数组,第一个矩阵位于r(:,:,1),第二个矩阵位于r(:,:,2),...(如果列数不能被 整除,则使用M(:,1:seg*segLen)instread of )。 生成一个 nrows-by-1-by-数组,再次从中生成一个 nrows-by-矩阵。MsegLenmean(r,2)segsqueezeseg

于 2013-02-21T16:11:36.983 回答
1

你可以arrayfun一起使用cell2mat

result = cell2mat(arrayfun(@(x,y) mean(M(:,x:y),2), segBeg, segEnd,...
   'UniformOutput', false))

这导致

result =

   1.0e+03 *

    0.0030    0.0145    0.0650
    0.0500    0.3500    1.2500
    0.0150    0.1500         0

其中每一列代表一个子矩阵的平均值。

另一个使用的解决方案blockproc(就像@DennisJaheruddin 在评论中建议的那样)可能看起来像这样

myFun = @(x) mean(x.data,2);

result2 = blockproc(M, [N, segLen], myFun)

这也导致

result2 =

   1.0e+03 *

    0.0030    0.0145    0.0650
    0.0500    0.3500    1.2500
    0.0150    0.1500         0

请注意,如果标志设置为,blockproc则可以利用并行处理,即'UseParallel'trueresult2 = blockproc(M, [N, segLen], myFun, 'UseParallel', true)

于 2013-02-21T15:59:09.797 回答
0

你可以为你的例子做

mean1 = mean(M(:,1:segLen))
mean2 = mean(M(:,segLen+1:N-segLen-1))
mean3 = mean(M(:,N-segLen:end)) 
于 2013-02-21T15:56:45.897 回答