- 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
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Stephen23
le 10 Fév 2015
Modifié(e) : Stephen23
le 10 Fév 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:
0 commentaires
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur String Parsing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!