【问题标题】:Skip data files while reading input and writing output in matlab code在 matlab 代码中读取输入和写入输出时跳过数据文件
【发布时间】:2015-06-17 18:36:15
【问题描述】:

我使用matlab代码读取几个文件并按如下方式写入输出:

n=202;
for idx = 0:n

    infilename = sprintf('pt%d.txt',idx);
    outname = sprintf('out%d.txt',idx);

现在,如果缺少一些任意数据文件,例如pt20.txt, pt50.txt 等然后代码被终止。我想以某种方式修改代码,如果找不到某些数据文件,那么代码将跳过它们并继续读取/写入下一个可用的数据文件。

谢谢。

【问题讨论】:

    标签: matlab


    【解决方案1】:

    您还可以使用exist 测试文件是否存在

    n=202;
    for idx = 0:n
        infilename = sprintf('pt%d.txt',idx);
        outname = sprintf('out%d.txt',idx);
        if exist( infilename , 'file') == 2
            do your stuff
        end
    end
    

    【讨论】:

    • 谢谢。我猜它不起作用,并且有语法错误。但是,如果我尝试 infilename = sprintf('pt%d.txt',idx);如果 exsit(infilename) 则一旦遇到丢失的数据文件,代码就会终止。因此,例如,如果第 8 个数据文件丢失,那么它会在遇到丢失的数据文件之前写入输出并终止。
    • 应该可以。如果文件不存在,for 循环将继续工作。您能否提供其余的 cde 以了解问题。
    • 您好,非常感谢。我想,以前有一个错字,在 "file" 之后缺少逗号。我刚刚注意到你编辑了那部分,我从来没有注意到丢失的 ' 。那是我的错。现在正在工作。再次感谢。
    【解决方案2】:

    试试this (see how to handle exceptions heading)

    for x:y
     try
       % do something ...
       break;
     catch
       fprintf('error occurs, retry...')
     end
    end
    

    【讨论】:

    • 谢谢。但这并没有解决问题。感谢您的链接
    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    相关资源
    最近更新 更多