필터 지우기
필터 지우기

How to save data from a file with text and numbers?

조회 수: 2 (최근 30일)
Abhiram B R
Abhiram B R 2021년 5월 14일
편집: per isakson 2021년 5월 16일
I have to load a file to Matlab with words and numbers and perform few operations. Structure of the file to be loaded is as follows:
Step
0
Number
1000
Box Dimension
0 10 0
10 0 0
0 0 10
ID Type
1 2
2 3
3 1
.....
i need to load this file and save lines starting from 'Step' to 'ID Type' to another file. Is it possible to do such operations in MATLAB?
  댓글 수: 2
Mathieu NOE
Mathieu NOE 2021년 5월 15일
sure
use readlines or fileread
T = fileread('data2.txt');
TT = split(T);
% or
TTT = readlines('data2.txt');
per isakson
per isakson 2021년 5월 15일
Here the tags shall not have a leading #.

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

채택된 답변

per isakson
per isakson 2021년 5월 15일
편집: per isakson 2021년 5월 16일
"load this file and save lines starting from 'Step' to 'ID Type' to another file" Including the "ID Type" block - or not ?
This script includes the "ID Type" block. I assume that the sample data is followed by a specific word. I've replaced the ending "...." with the string "Something else".
%%
chr = fileread( 'Untitled3.txt' );
txt = regexp( chr, '^.+(?=Something else)', 'match','once' );
fid = fopen( 'another_file.txt', 'wt' );
fprintf( fid, '%s', txt );
fclose( fid );
type another_file.txt
Step 0 Number 1000 Box Dimension 0 10 0 10 0 0 0 0 10 ID Type 1 2 2 3 3 1
"and perform few operations" In what form do you want which data?
Second thought:
The function, regexp(), is powerful and fast but not the easiest to get the hang of. In this case the statement
txt = regexp( chr, '^.+(?=Something else)', 'match','once' );
can be replaced by
pos = strfind( chr, 'Something else' );
txt = chr(1:pos(1)); % pos(1) in case there are many 'Something else' in the file
or
txt = extractBefore( chr, 'Something else' );
I should have used extractBefore() in my answer. It's easy to use and fast.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by