Save lines from a text file

20 ビュー (過去 30 日間)
Guido Pozzi
Guido Pozzi 2019 年 10 月 21 日
回答済み: Stephan 2019 年 10 月 21 日
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 Center および File ExchangeTables についてさらに検索

製品


リリース

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by