How to read in data from file using specific lines?

12 ビュー (過去 30 日間)
Manny
Manny 2021 年 3 月 24 日
編集済み: Manny 2021 年 3 月 24 日
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

採用された回答

DGM
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 件)

カテゴリ

Help Center および File ExchangeData Import and Export についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by