read a text file

조회 수: 2 (최근 30일)
Postit123
Postit123 2020년 11월 4일
답변: Pratheek Punchathody 2020년 11월 18일
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.
  댓글 수: 1
Walter Roberson
Walter Roberson 2020년 11월 4일
See https://www.mathworks.com/help/matlab/ref/matlab.io.text.fixedwidthimportoptions.html

댓글을 달려면 로그인하십시오.

채택된 답변

Pratheek Punchathody
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.
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.
“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.
Refer to the Documentation - detectImportOptions for further information.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Migrate GUIDE Apps에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by