Reading a Column Vector of Strings from a *.txt file in Linux

1 view (last 30 days)
Working on Ubuntu.
have a text file example.txt of the form:
string1
string2
string3
...
To read into a column vector do:
fileID=fopen('/home/data/example.txt');
formatSpec='%s\n';
example==fscanf(fileID,formatSpec);
Unfortunately variable looks like:
string1string2string3...
What am I doing wrong?

Accepted Answer

Stephen23
Stephen23 on 10 Feb 2015
Edited: Stephen23 on 10 Feb 2015
This is the documented behavior for fscanf : If formatSpec contains only character or string specifiers (%c or %s), then A is a character array. The strings are not separated by other (extra) characters, nor are they in a cell array: the documentation does not mention anything about such things, only that they will be returned in a character array. So in your case it reads each string (group of characters) in the file that is separated by newlines, and returns only these together in one long string, nothing more.
You could:
  • use fscanf with the optional third input to determine the output (char) array size. This works if you know something about the length of the rows. It is also very fast.
  • try textscan, which may be a more intuitive to use, and has the advantage of being platform independent (if you use the text option: fopen(filename,'rt') ).
  • try fileread , which returns the whole file as a string: you could then use regexp to split the output string into a cell array of each separate substring.
  • try importdata, although the behavior of this depends on the contents of each of the lines in the file, and it may give unexpected results.
  • have a look at all of the other file-reading functions, and pick one that suits your needs.

More Answers (1)

Luuk van Oosten
Luuk van Oosten on 10 Feb 2015
Hi,
A suggestion:
a(:,1) = importdata('yourdata.txt')

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!