What is the effective error block statements when import many kinds of txt data?

Hi,
In my function, it import many text data and save it.
data1=importdata('data1.txt');
data2=importdata('data2.txt');
........
data100=importdata('data100.txt');
But in special case, there are some missing txt files so this error msg occurs.
Error using importdata (line 136)
Unable to open file.
so I have to block this error.
To use try/catch, all the 'import data' lines have to add try/catch.
try
data1=importdata('data1.txt');
catch
data1=0;
try
data2=importdata('data2.txt');
catch
data2=0;
........
try
data100=importdata('data100.txt');
catch
data100=0;
This would be very annoying and inefficient method. Is there are idea for solving this problem??

 Accepted Answer

For a start this is one of the reasons why you absolutely should not create 100 different variables to load your data into.
Either use a numeric array or, if the data are different size, use a cell array of 100 indices.
Then you can do something more like this:
for n = 1:100
try
filename = [ 'data', num2str( n ), '.txt' ];
data{n}=importdata('data1.txt');
catch err
data{n} = 0;
end
end
try-catch blocks can be expensive in runtime though so simply checking if the file exists first would likely be more efficient if the only error you expect is from missing files.
I added the 'err' to the catch just because I would usually catch the error and try to deal with specific errors rather than just catch all errors, but if your aim is simply to put a 0 in if anything at all goes wrong on trying to load data then there is no need to do that in the try-catch approach.

4 Comments

I think you meant "you absolutely should NOT create 100 different variables".
In matlab, exceptions are probably no more expensive than a lot of other constructs. In any case, compared to file io, it's going to be dirt cheap.
Oops, yeah, I've edited my answer now to correct that.
As for try-catch, yeah, I have only really looked into their time taken once and it added a huge amount to what I was doing, but I was just doing maths in a loop in a try-catch rather than file IO so there the overhead of try-catch was significant. I haven't looked at its overhead in more detail though.
It is also recommended to preallocate cell arrays, which would also make this code simpler (I also fixed that filename was unused in the Answer above):
data = repmat({0},1,100);
for n = 1:100
try
filename = [ 'data', num2str( n ), '.txt' ];
data{n} = importdata(filename);
end
end

Sign in to comment.

More Answers (0)

Categories

Asked:

on 21 Jan 2016

Edited:

on 23 Jan 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!