Save lines from a text file
조회 수: 20 (최근 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
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
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!