我怎样才能更有效率

how can I be more efficient

如何才能更高效地编写以下 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

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

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) > 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 或更大的值都可以。)