在for循环+ matlab中,continue语句没有正确执行

时间:2014-01-05 21:31:32

标签: matlab for-loop continue

我有以下代码:

for i=1:length(files)
    for j=1:length(files(i,1).day)
        if ((1:length(files(i,1).day(j).hour)) ~=  24)
            continue
        end
        for h = 1:24
            if ((1:length(files(i,1).day(j).hour(h).halfhour)) ~= 2)
                continue
            end

            if isempty(1:length(files(i,1).day(j).hour))
                continue
            end
            dayPSD = [];
            for h2=1:2
                dayPSD = [dayPSD; files(i,1).day(j).hour(h).halfhour(h2).data{8}'];
            end
        end
    end
end

,其中

  files=1x3 structure
  files(i,1).day=1x335 structure that contains 1 field hour which is a 1x24 structure
  files(i,1).day.hour=1x24 structure that contains 1 field halfhour which is a 1x2 structure

我试图遍历i和j,但是当1:length(文件(i,1).day(j).hour)〜= 24(所以当小时数小于24时)我想退出循环并继续执行for循环的下一次迭代。我也希望它退出循环并继续到for循环的下一次迭代,如果1:length(files(i,1).day(j).hour(h).halfhour)〜= 2(所以当半小时小于2)或如果1:长度(文件(i,1).day(j).hour是一个空单元格(没有数据)。

我写的当前代码似乎只跳过循环索引,如果1:length(files(i,1).day(j).hour~ = 24。

我做错了什么?如果符合任何条件,我如何让它继续下一次迭代?我一直在敲打这个问题一段时间,我知道我可能犯了一个简单的错误,但是如果有人能指出我的方向会很好。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你想要的是:

for i=1:length(files)
    for j=1:length(files(i,1).day)
        if ((1:length(files(i,1).day(j).hour)) ~=  24)
            continue
        end
        for h = 1:24
            if ((length(files(i,1).day(j).hour(h).halfhour)) ~= 2)
                break
            end

            if isempty(files(i,1).day(j).hour)
                break
            end
            dayPSD = [];
            for h2=1:2
                dayPSD = [dayPSD; files(i,1).day(j).hour(h).halfhour(h2).data{8}'];
            end
        end
    end
end

因此,当满足任一条件时,执行流程将退出for h=..循环,并且由于for j=1...循环中没有其他语句,代码实际上将跳过该迭代。 / p>

另请注意,if ((1:length(files(i,1).day(j).hour(h).halfhour)) ~= 2)正在将向量(1:length(..))与标量2进行比较,从而生成布尔值向量。 if部分只有在true的所有元素都是{{1}}时才会被执行。