我怎样才能更有效率

时间:2015-05-26 16:26:49

标签: matlab for-loop indexing while-loop

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

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

1 个答案:

答案 0 :(得分:0)

这会产生与您的代码相同的结果:

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没有固定值的情况,只要s是有效索引或大于零,我们就希望继续递增i-(s+1)+1是因为我们立即在循环中递增它。这意味着我们需要(i-s) > 1,我们可以从for而不是1开始maxBack+1循环。

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或更高都可以。)

相关问题