【问题标题】:how can I be more efficient我怎样才能更有效率
【发布时间】:2015-05-26 16:26:49
【问题描述】:

如何在下面的 Matlab 代码中提高效率?使用while循环?为了我的目的,我将不得不继续添加更多 if 语法。任何帮助将非常感激。

TimeLagM = 6;2;3;1;2;10;25;60;2;5;10;80;24;1;2;3;

p=0;
count=zeros(length(TimeLagM),1));

for i=4:length(TimeLagM)
    if TimeLagM(i,1)>30
    count(i,1)=count(i,1)+0;
    elseif TimeLagM(i,1)==30
    count(i,1)=count(i,1)+1;
    elseif TimeLagM(i,1)<30
        p=TimeLagM(i,1)+TimeLagM(i-1,1);
        if p>30
        count(i,1)=count(i,1)+1;
        elseif p==30
        count(i,1)=count(i,1)+2;
        elseif p<30
            p=p+TimeLagM(i-2,1);
            if p>30
            count(i,1)=count(i,1)+2;
            elseif p==30
            count(i,1)=count(i,1)+3;
            elseif p<30
                p=p+TimeLagM(i-3,1);
                if p>30
                count(i,1)=count(i,1)+3;
                elseif p==30
                count(i,1)=count(i,1)+4;
                elseif p<30
                count(i,1)=count(i,1)+5;

                end 
            end
         end
    end
end

【问题讨论】:

  • elseif p

标签: matlab for-loop indexing while-loop


【解决方案1】:

这给出了与您的代码相同的结果:

TimeLagM = [6;2;3;1;2;10;25;60;2;5;10;80;24;1;2;3];

thresh = 30;
maxBack = 3;

p=0;
count=zeros(length(TimeLagM),1);

for i=maxBack+1:length(TimeLagM)
   p = TimeLagM(i);
   s = 0;
   while (s < maxBack && p < thresh)
      s = s + 1;
      p = p + TimeLagM(i-s);
   end

   if p > thresh
      count(i) = count(i) + s + 0;  % i don't know what these values mean
   elseif p == thresh               % so i couldn't give them meaningful names
      count(i) = count(i) + s + 1;
   else % p < thresh
      count(i) = count(i) + s + 2;
   end
end

while 循环计算p 中的总和并记住它必须返回s 中的多少元素。这样你只需要在一个地方计算count。这假设count 将来可能会被初始化为非零的值;否则,您可以将分配缩短为 count(i) = s + 0(或 1 或 2)。

给定数据的结果是:

count' =

   0   0   0   5   5   5   1   0   1   2   3   0   1   2   3   4

对于maxBack 没有固定值的情况,只要i-(s+1) 是有效索引或大于零(+1 是因为我们立即在循环中增加它)。这意味着我们需要(i-s) &gt; 1,我们可以从1而不是maxBack+1开始for循环。

for i=1:length(TimeLagM)
   ...
   while ((i-s) > 1 && p < thresh)
   ...

如果您想保留两者都做的选项,是否有固定的maxBack,您可以在while 循环中包含所有三个条件:

   while ((i-s) > 1 && s < maxBack && p < thresh)

然后,如果您不想指定maxBack,只需设置maxBack = intmax。 (实际上,length(TimeLagM) - 1 或更大的任何值都可以。)

【讨论】:

  • 这太棒了!感谢“烧杯......当 maxBack 未知时的任何建议
  • 您希望返回的元素数量仅受输入矩阵的范围限制?
  • 如果我们只知道 sum 最大为 30(即 thresh=30)但不知道 maxBack =3
  • 如果它解决了您的问题,请务必接受答案。
猜你喜欢
  • 2015-12-23
  • 2011-11-08
  • 2010-11-14
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-10
  • 1970-01-01
相关资源
最近更新 更多