Save lines from a text file

10 views (last 30 days)
Guido Pozzi
Guido Pozzi on 21 Oct 2019
Answered: Stephan on 21 Oct 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 Comment
Ruger28
Ruger28 on 21 Oct 2019
check out
fgetl
and use a while loop. You can read each line and store it away as needed until file is finished.

Sign in to comment.

Accepted Answer

Stephan
Stephan on 21 Oct 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"

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2015b

Community Treasure Hunt

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

Start Hunting!