MATLAB: How to replace ‘textread’ with ‘textscan’

MATLAB

I heard that 'textread' is not recommended, but I am having trouble replacing it with 'textscan'.

Best Answer

The 'textscan' function offers several advantages over 'textread'.
1. It is much more efficient, especially when reading very large files or a very large number of files
2. It has more features and supports more types and formats
3. It offers greater flexibility when reading from arbitrary points in the file.
4. Using fopen/fclose offers more power and safety in dealing with files and errors.
Your original code might look something like this:
[x,y,z] = textread(filename,format);
When using 'textscan', you must open the file with 'fopen' first and close it later. In addition, the output is returned as a cell array instead of separate output variables.
Your new code might look something like this:
fid = fopen(filename);
C = textscan(fid,format);
fclose(fid);
[x,y,z] = C{:};
There is likely no need to go back and rewrite all of your old code to use 'textscan' instead, but future code should. However, you may still want to do this if you desire the features, stability, and performance of 'textscan' in your older code. For example if you are reading very large files or a very large number of files you may find that the significant speedup is worth the effort in some cases.