read a text file
1 次查看(过去 30 天)
显示 更早的评论
Hi
I need to make a matrix with the text file attached below.
I've considered 'fscanf' and 'readtable'.
But I faced 2 problems.
Some of rows have 8 elements while others have 10.
Also, there are blank cells and I don't know how to handle this to make it 0.
Thanks.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/402920/image.png)
1 个评论
Walter Roberson
2020-11-4
See https://www.mathworks.com/help/matlab/ref/matlab.io.text.fixedwidthimportoptions.html
采纳的回答
Pratheek Punchathody
2020-11-18
As per my understanding it is required to create a matrix/table from the data present in the text file.
For the demo purpose I have taken the sample text file which has different number of columns in each row and there are multiple empty cells in each row.
Considering the sample text file with the data as shown below.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/418098/image.jpeg)
Below is the code I have used to import the text file to a matrix.
opts = detectImportOptions('same.txt', 'EmptyLineRule','skip','ExtraColumnsRule','ignore');
opts.MissingRule = 'fill';
opts = setvaropts(opts,'FillValue',0); %fill the empty cells with the value 0
myTable = readtable('same.txt',opts); %create table from the .txt file
myMatrix=table2array(myTable); %create from the table
Below image shows the output matrix of the data present in the text file.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/418103/image.jpeg)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/418108/image.jpeg)
“table2array()” function is used to convert the created table to matrix format.
As required, all the empty cells adn extra column cells are filled with 0.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!