【问题标题】:Matlab: nested loops with if conditionalMatlab:带有if条件的嵌套循环
【发布时间】:2016-10-03 05:08:45
【问题描述】:

我正在尝试通过迭代大小为 (50000, 21) 的主矩阵中最后一列的行来构建子矩阵,如果里面的值大于 1000,则整个对应的 y(i, :) 行将被添加到新的子矩阵中,并从主矩阵中添加更多的 33 行。

我在下面编写了这段代码,但它只返回 33x21 大小,我认为我正在迭代 j 索引而不是 i 索引:

for i=1:50000
  if y(i,21)>1000
  for j=1:33
    n(j,:)=y(j+i,:)
    j=j+1
  end
  i=i+1
end
end

我做错了什么?

【问题讨论】:

    标签: matlab loops matrix


    【解决方案1】:

    试试这个:

    k=1;
    for i=1:50000
        if y(i,21)>1000
            for j=0:33 %watch this out i am not sure how many rows you want to keep and if these involve the one with the last element greater than 1000 or not..%
                n(k,:)=y(j+i,:);
                j=j+1;
                k=k+1;
            end
        i=i+1;
        end
    end
    

    问题是每组新的 33 行都会覆盖前一个。我认为上面的代码可以解决问题。

    【讨论】:

      【解决方案2】:

      这是一个不需要循环的矢量化版本:

      %find elements that are greater than 1000
      lo = find(y(:,21) > 1000);
      %indeices of 33th row after the lo,
      %since it may take a value that is greater than the size of matrix we limit this value by min
      up = min(size(y,1), lo + 33);
      % create indices based on ranges
      %see http://stackoverflow.com/a/39434045/6579744
      index=cumsum(accumarray(cumsum([1;up(:)-lo(:)+1]),[lo(:);0]-[0;up(:)]-1)+1);
      index= index(1:end-1);
      n = y(index, :)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        • 2018-07-08
        • 1970-01-01
        • 2021-09-26
        • 1970-01-01
        • 2017-12-20
        相关资源
        最近更新 更多