Read text file and save result

조회 수: 4 (최근 30일)
Maryam Hamrahi
Maryam Hamrahi 2016년 6월 2일
댓글: Maryam Hamrahi 2016년 6월 2일
I want to read X and Y axis from a text file, store them in a matrix, and then use "fprintf" to save the results.
I do not want to use "identifier" in the code.
This is the text:
2 # version
2 # sdim
10 # number of points
0 # lowest mesh point index
point coordinates
0 0
0 0.10000000000000001
0.064252773249227707 0.067458641273279954
0.099999999999998201 0
0 0.20000000000000001
0.1999999999999984 0
0.072503096519224278 0.14995795459895683
0.14876076972691604 0.087335251767442917
0.072596698771222157 0.25014136767117334
0 0.30000000000000004
I appreciate any suggestion.
Thank you in advance.
  댓글 수: 1
Maryam Hamrahi
Maryam Hamrahi 2016년 6월 2일
I use the following code. I want to modify the code without using "identifier".
function [PointMatrix] = m ( ~ )
i = 1;
identifier = {' point coordinates'};
addpath('C:\Users \Desktop');
fid = fopen(strcat(point '. txt'));
while ~feof(fid)
readLine = cellstr(fgets(fid));
if strcmp(readLine, identifier(1))
while(~strcmp(readLine, cellstr('')))
readLine = cellstr(fgets(fid));
Point(i, :) = readLine;
i = i+1;
end
Point(end, :) = [];
for i = 1:size(meshPoint, 1)
PointMatrix(i, :) = str2num(cell2mat(Point(i)));
end
clear 'Point';
i = 1;
end

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

답변 (1개)

Walter Roberson
Walter Roberson 2016년 6월 2일
infmt = '%f%f';
headers = 5;
fid = fopen('YourFile.txt', 'rt');
datacell = textscan(fid, infmt, 'HeaderLines', headers, 'CollectOutput', 1);
fclose(fid);
YourVariable = datacell{1};
save('AppropriateFile.mat', 'YourVariable');
outfmt = '%g %g\n';
fprintf(outfmt, YourVariable .' );
  댓글 수: 10
Walter Roberson
Walter Roberson 2016년 6월 2일
You can answer the question about why it is important to not use '# Mesh point coordinates' .
Maryam Hamrahi
Maryam Hamrahi 2016년 6월 2일
Because I want to read different parts of the code like "# Geometric entity indices"
when I use the following
identifier = {'# Mesh point coordinates','# Geometric entity indices'};
The code could not read "# Geometric entity indices".
So, I want to avoid using "identifier" and write the code in a different way.
Please see the attached file, this text file is much simpler.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by