Read text file and save result

1 次查看(过去 30 天)
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 中查找有关 Text Data Preparation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by