How to read in data from file using specific lines?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
채택된 답변
DGM
2021년 3월 24일
편집: DGM
2021년 3월 24일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Import and Export에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!