【问题标题】:Adding multiple nth elements of a matrix repeatedly重复添加矩阵的多个第 n 个元素
【发布时间】:2011-11-15 19:08:24
【问题描述】:

我有一个 63 行 x 7 列的矩阵

我想在每列中选择每第 7、8、9 个正在进行的值并将它们添加以创建一个新值。

7 8 9th 添加到新值

16 17 18th 添加到新值...等

25 26 27 日

34 35 36

43 44 45

52 53 54

61 62 63

所以我应该得到一个 7x7 矩阵。

如果不手动执行此操作,是否有一个简单的命令,以便在矩阵的维度发生变化时,输出始终正确?

【问题讨论】:

    标签: matlab matrix addition


    【解决方案1】:

    你可以通过一些重塑来轻松做到这一点。

    originalMatrix = (1:63)'*(1:7); %'
    [nRows,nCols] = size(originalMatrix); %# =63 in this example
    stepSize = 9;
    nTriplets = floor(nRows/stepSize); %# =7 in this example
    
    %# create index list
    idx = bsxfun(@minus,stepSize:stepSize:nRows,[2 1 0]'); %'
    idx = idx(:); %# reshape to a vector
    
    %# create 3-by-7-by-7 array from original matrix
    tmpMatrix = reshape(originalMatrix(idx,:),3,nTriplets,nCols);
    
    %# sum along dim 1 (to sum e.g. the 7th, 8th, and 9th value)
    result = squeeze(sum(tmpMatrix,1));
    
    result =
          24          48          72          96         120         144         168
          51         102         153         204         255         306         357
          78         156         234         312         390         468         546
         105         210         315         420         525         630         735
         132         264         396         528         660         792         924
         159         318         477         636         795         954        1113
         186         372         558         744         930        1116        1302
    

    【讨论】:

      【解决方案2】:
      matrix=(1:63)'*(1:7);
      n=7;
      
      startind = n:(n+2):size(matrix,1);
      endind = (n+2):(n+2):size(matrix,1);
      tmp=cumsum(matrix);
      tmp(endind,:)-tmp(startind,:)
      

      当然,这仅在 startindendind 具有相同长度时才有效,例如,对于大小为 62x7 的矩阵,情况并非如此。

      【讨论】:

        【解决方案3】:

        如果我正确理解了您的问题,那么这段代码应该可以满足您的需求。但我承认,也许它不是有史以来最高效的 Matlab 代码......

        k = 9; n = 7; m = k*n; % 63
        A = randi(5,m,n);
        
        startIdx = k*(1:n)+n-k;
        endIdx = k*(1:n);
        
        B = zeros(n,n);
        for i = 1:n
            tmp = A(startIdx(i):endIdx(i),:);
            B(i,:) = sum(tmp,1);
        end
        

        【讨论】:

          猜你喜欢
          • 2020-09-06
          • 1970-01-01
          • 2021-02-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-14
          • 2019-12-24
          • 1970-01-01
          相关资源
          最近更新 更多