How to read in data from file using specific lines?
12 views (last 30 days)
Show older comments
Hi! I have a project dealing with plotting bezier curves from a data file. The first value of the data file (data.m) is the number of curves that will be plotted on the graph which I already coded. Then each set of lines correspond to the x and y values. I am trying to read this data into my program by calling out the odd lines for the x's and even lines for the y's. However it is not working and I didn't take into account the spaces. How can I be able to read in this data file into my program in order to sucessfully run in? I can easily hard code it but unfortunately cannot do that as when my program will be tested, the numbers of the file will be different.
data.m (NOTE: comments are not actually on the file! Just adding them to describe the values)
3 %number of curves
0 0 0 0 %x values
0 3 3 6 %y values
0 4 4 0 %x values
6 6 3 3 %y values
0 1.5 1.5 3 %x values
3 1.5 1.5 0 %y values
0 Comments
Accepted Answer
DGM
on 24 Mar 2021
Edited: DGM
on 24 Mar 2021
I'll leave the matter of how you choose to plot the data up to you, but this is one way to get the file read:
% open file and grab everything
fid = fopen('data.m','r'); %open file
lines=textscan(fid,'%s','Delimiter','\n');
fclose(fid); %close file
% get rid of blank lines and reformat for more convenient indexing
lines=lines{:}(~cellfun(@isempty,lines{:}))
numcurves=str2double(lines{1});
for c=1:numcurves
% grab the vectors from the cell array
thisx=str2num(lines{2+(c-1)*2});
thisy=str2num(lines{3+(c-1)*2});
% do stuff with these vectors
% plot them, etc...
end
Something like that should work.
0 Comments
More Answers (0)
See Also
Categories
Find more on Data Import and Export in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!