Save lines from a text file

15 visualizaciones (últimos 30 días)
Guido Pozzi
Guido Pozzi el 21 de Oct. de 2019
Respondida: Stephan el 21 de Oct. de 2019
Hi.
I have a txt file that looks like this:
Darby George 166.2
Helen Dee 143.5
Giovanni Lupa 192.4
Cat Donovan 215.1
How can I save each of these lines into a different string variable ? but without knowing how many lines the txt file has.
The answer from MATLAB should look like this
a=Darby George 166.2
b=Helen Dee 143.5
c=Giovanni Lupa 192.4
d=...
e=..
Thanks
  1 comentario
Ruger28
Ruger28 el 21 de Oct. de 2019
check out
fgetl
and use a while loop. You can read each line and store it away as needed until file is finished.

Iniciar sesión para comentar.

Respuesta aceptada

Stephan
Stephan el 21 de Oct. de 2019
It is a bad idea to store the lines all in different variables - this point has been discussed here for many times... Use a table or a cell array and then take advantage of the many functions that will make life easier:
fileID = fopen('text.txt');
A =textscan(fileID, '%s %s %f');
fclose(fileID);
A = table(A{:},'VariableNames',{'Name','LastName','Score'});
A.LastName = string(A.LastName);
A.Name = string(A.Name)
I saved your data i a file named text.txt - the result of this code is:
A =
4×3 table
Name LastName Score
__________ _________ _____
"Darby" "George" 166.2
"Helen" "Dee" 143.5
"Giovanni" "Lupa" 192.4
"Cat" "Donovan" 215.1
Believe me - this is what you want, if you only learn indexing included logical indexing:
>> A(A.Name=="Cat",:)
ans =
1×3 table
Name LastName Score
_____ _________ _____
"Cat" "Donovan" 215.1
>> A.Name(A.LastName == "Lupa")
ans =
"Giovanni"
>> A.Name(A.LastName == "Dee")
ans =
"Helen"
>> A.Name(A.Score==143.5)
ans =
"Helen"

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Productos


Versión

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by