尝试在Matlab中捕获块

mot*_*iur 7 matlab

所以,我正在阅读数百个图像文件imread('D:\pic1\foo.jpg'),其中一些就像imread('D:\pic2\Thumbs.db').阅读后我将存储在这样的数据库中,train(i) = imread('D:\pic1\foo.jpg').问题在于imread('D:\pic2\Thumbs.db'),读取这些文件显然会出错.我想像这样缓解这个问题:

for i=1:N
  try
    train(i) = imread(link{i})

    %link{i} can be 'D:\pic2\Thumbs.db' or 'D:\pic1\foo.jpg'

  catch 
    disp('Error')
  end
end
Run Code Online (Sandbox Code Playgroud)

问题出在这里的try块中.有两件事正在发生,一件是读取文件另一件是分配imread值train(i).现在,这很重要,只有成功imread()应该有一个任务,失败时会出现错误.Matlab通过catch块来处理错误,没有一个块来处理我可以完成赋值的成功条件,这样我就可以毫不费力地读写.

我想要这样的东西:

j = 0;
for i=1:N

  try:
   imread(links{i})

  if success:
   train(j) = imread(links{i})
   j = j+1;

  if fail:
   error
  end

end
Run Code Online (Sandbox Code Playgroud)

我只是在搜索Matlab文档时想出了尝试和捕获,如果有任何东西可以帮助我简洁地编写代码,我将非常感激.

Jon*_*nas 11

@gnovice解决方案是正确的,但它可以更简洁地编写:

ct = 1;
for i=1:N

  try
   train(ct) = imread(links{i});
   ct = ct +1; %# if imread fails, this line is not executed

  catch me
    %# report the problematic image, and the reason for failure
    fprintf('image #%i (%s) cannot be opened: %s\n',i,links{i},me.message)
  end

end
Run Code Online (Sandbox Code Playgroud)