How do I extract fixed-width columns from a file that includes empty spaces?

조회 수: 5 (최근 30일)
deathtime
deathtime 2022년 8월 16일
답변: Benjamin Thompson 2022년 8월 16일
I have a file called gridpoints.txt. It is structured as follows:
$$ GRID Data
GRID 100 6956.519 492.02359.538
GRID 101 7366.59 492.02359.53
GRID 102 6976.51 492.02 59.538
After the single header line above, the data block segment begins, with each line in this segment beginning with "GRID". There are thousands of similar lines in the file that follow.
In this data block segment, there are 6 fixed-with columns, each 8 characters long - and this includes the empty spaces. For example, the column entries of the first data block row are:
column 1 entry: "GRID "
column 2 entry: " 100"
column 3 entry: " "
column 4 entry: "6956.519"
column 5 entry: " 492.0"
column 6 entry: "2359.538"
Essentially I am trying to capture the numbers contained in columns 4, 5 and 6 and store in cell arrays. Across all the rows, the number of empty characters within each fixed width column can vary, as can be seen in the file content sample above.
What is the most straightforward way to do this?
Thank you.
  댓글 수: 1
Dyuman Joshi
Dyuman Joshi 2022년 8월 16일
You can use str2num
%using data directly, edit according to use
x=["6956.519";" 492.0";"2359.538"];
y=cell(1,numel(x));
for i=1:numel(x)
y{i}=str2num(x(i));
end
y
y = 1×3 cell array
{[6.9565e+03]} {[492]} {[2.3595e+03]}

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

답변 (1개)

Benjamin Thompson
Benjamin Thompson 2022년 8월 16일
Use the import data tool and configure the delimiter options to use space and treat multiple delimiters as one. You can generate sample code from that to reuse on other files.

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by