Save lines from a text file

10 次查看(过去 30 天)
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 个评论
Ruger28
Ruger28 2019-10-21
check out
fgetl
and use a while loop. You can read each line and store it away as needed until file is finished.

请先登录,再进行评论。

采纳的回答

Stephan
Stephan 2019-10-21
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"

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品


版本

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by