Clear Filters
Clear Filters

Read text file and save result

1 view (last 30 days)
Maryam Hamrahi
Maryam Hamrahi on 2 Jun 2016
Commented: Maryam Hamrahi on 2 Jun 2016
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 Comment
Maryam Hamrahi
Maryam Hamrahi on 2 Jun 2016
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

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 2 Jun 2016
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 Comments
Walter Roberson
Walter Roberson on 2 Jun 2016
You can answer the question about why it is important to not use '# Mesh point coordinates' .
Maryam Hamrahi
Maryam Hamrahi on 2 Jun 2016
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!