- 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.
Reading a Column Vector of Strings from a *.txt file in Linux
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Stephen23
2015-2-10
编辑:Stephen23
2015-2-10
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:
0 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!