用Matlab在循环内更改循环

时间:2018-08-24 10:54:31

标签: matlab performance loops for-loop

我浏览了Matlab手册和各种帖子,但似乎没有合适的内容。您可以在下面找到有问题的代码。

我的代码运行良好,但是,我不确定Year和PartOfYear的循环。我希望我的代码针对Year = 2008:2016和PartOfYear = 1:2运行,但是,当Year = 2017时,它应仅针对PartOfYear = 1运行。即,当Year = 2017时,没有PartOfYear = 2。 有没有更有效的方法(甚至是正确的方法,因为我的方法可能不正确)? 此刻,我只是尝试每次在Year = 2017时再次运行PartOfYear = 1,PartOfYear = 2,因此只需将这部分代码执行两次,但是我认为这是不正确的,而且效率很低,因为结果似乎离开。

谢谢!

for index = 1:20

StartYearData = 2008;
EndYearData = 2017;

for Year = StartYearData:EndYearData
    for PartOfYear = 1:2

        if PartOfYear == 1
            StartDayData = 1;
            StartMonthData = 1;
            EndDayData = 30;
            EndMonthData = 6;

        elseif PartOfYear == 2
            StartDayData = 1;
            StartMonthData = 7;
            EndDayData = 31;
            EndMonthData = 12;

            % THIS IS THE WAY I USE TO TRY AND FIX MY PROBLEM
            % BUT I BELIEVE IT IS WRONG OR AT LEAST INEFFICIENT:
            if Year == 2017
                PartOfYear = 1; StartDayData = 1; StartMonthData = 1;
                EndDayData = 30; EndMonthData = 6;
            end
        end 

% DO A LOT OF THINGS

end

1 个答案:

答案 0 :(得分:1)

您不能在循环内部更改循环变量。看来您只是对循环的顺序和if语句感到困惑。

有很多方法可以实现您的要求。这段代码应该可以满足您的要求,并且在PartOfYear = 1时仅使用=1:2(而不是Year = 2017

for index = 1:20    
    StartYearData = 2008;
    EndYearData = 2017;    
    for Year = StartYearData:EndYearData 
        % If the year is 2017, we only want to use PartOfYear=1, otherwise 1:2
        if Year == 2017
            parts = 1;
        else
            parts = 1:2;
        end
        % Now we can loop over the 'parts', which is either 1 or 1:2
        for PartOfYear = parts 
            StartDayData = 1;   % This is the same regardless of PartOfYear value 
            if PartOfYear == 1
                StartMonthData = 1;
                EndDayData = 30;
                EndMonthData = 6;    
            elseif PartOfYear == 2
                StartMonthData = 7;
                EndDayData = 31;
                EndMonthData = 12;    
            end     
            % Stuff...
        end
    end
end