MATLAB Answers


How to read a text file into a char array

Asked by Paolo Binetti on 22 Jan 2017
Latest activity Commented on by Paolo Binetti on 22 Jan 2017
This is probably trivial, but I have not found an easy way to convert a text file of n lines and m columns (sample attached) into a char array of the same shape. The only way that might work for me is an n-long for-loop of "fscanf", but I do not know n beforehand, and I figure there must be a simpler and faster vectorized command, which I ignore (I tried fileread and textread to no avail).


Sign in to comment.

1 Answer

Answer by Walter Roberson
on 22 Jan 2017
 Accepted Answer

temp = regexp(fileread('sample_input.txt'), '\r?\n', 'split');
output = vertcat(temp{:});


Good that I asked, my several attempts were way off! One question: what is the purpose of "?" ? I have tried without, and it also works.
The \r represents carriage return. I did not bother to check whether your file has those or only newlines (and it is really easy end up accidentally having a mix of files) so I made the carriage return optional which is done by adding a ? after it.
An alternative to the \r?\n for your situation would be \W+ which would mean any sequence of consecutive non-"word" characters. That would also cover the case where you had multiple columns separated by blanks that you wanted to treat the same as if each were its own line.
Thank you, clear and useful.

Sign in to comment.