Reading only numeric data in a text file

조회 수: 11 (최근 30일)
Mahi Nazir
Mahi Nazir 2014년 11월 5일
댓글: Orion 2014년 11월 6일
I have a formatted text file (attached). I have to read it, ignoring some bits like the headings. After reading I should be able to get tx=2
ty=18
and the 4x4 matrix which is there in the text file. Rest of the strings like the headings, sensor1, chirp1 etc must be ignored.
How can I do this?

채택된 답변

Orion
Orion 2014년 11월 5일
it's almays more complicated to read a file with no defined data structure.
In your case, you can use (and adjust for other files)
% read the file
fid = fopen('FrequencyShiftsV1.txt','r');
MyTextFile = textscan(fid,'%s','delimiter','\n');
fclose(fid);
MyTextFile = [MyTextFile{:}];
% get and evaluate the lines 2 and 3 (matlab expression).
eval(MyTextFile{2});
eval(MyTextFile{3});
% extract the part containg the matrix to read
MatrixLines = MyTextFile(7:end);
% get rid of Chirp1, Chirp2, ...
MatrixLines = regexprep(MatrixLines,'Chirp[^%d]','');
% Convet the char into a numerical matrix.
MyMatrix = str2num(cell2mat(MatrixLines));
  댓글 수: 2
Mahi Nazir
Mahi Nazir 2014년 11월 6일
Brilliant thanks a lot!
Now if my text file changes to say tx=2
ty=18
N=3 and I have 3 4x4 matrices then or say if N=n, I will have n 4x4 matrices... Do I simply put a for loop? kindly help
Orion
Orion 2014년 11월 6일
if there are more lines
chirp5 ...
chirp6 ...
...
chirpN ...
it will be read and converted by the command MatrixLines = MyTextFile(7:end);
so you will get a Nx4 numerical array.
just manipulate it to create all your matrices.
if N = 12, means 3 matrices:
for i = 1 : 3
SubMat{i} = MyMatrix(1+4*(i-1):4+4*(i-1),:);
end

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by