- 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 visualización (últimos 30 días)
Mostrar comentarios más antiguos
A.
el 10 de Feb. de 2015
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 comentarios
Respuesta aceptada
Stephen23
el 10 de Feb. de 2015
Editada: Stephen23
el 10 de Feb. de 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 comentarios
Más respuestas (1)
Luuk van Oosten
el 10 de Feb. de 2015
Hi,
A suggestion:
a(:,1) = importdata('yourdata.txt')
0 comentarios
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!