Newline creates new data set
6 次查看(过去 30 天)
显示 更早的评论
I'd like to read a data set from a file that has headers at the top, and then columns of data. Once read in, this data will be plotted using a line plot. I would like a newline in the file to automatically create a new data set in the plot. If the data is not separated into separate data sets, the line plot becomes very confusing because it connects the end of one data set to the beginning of the next data set. Is there a way to do what I would like quickly in matlab? Or will I need to write my own script that parses the data according to the newline? I know this is a built in function for gnuplot which has been extremely helpful in the past.
0 个评论
回答(2 个)
Jan
2011-10-25
This can be done by a function easily:
FID = fopen(FileName, 'r');
if FID == -1; error('Cannot open file'); end
% Skip the header:
Data = cell(1, 1000); % Pre-allocate, hope we get less than 1000 lines
fgetl(FID);
i = 0;
while 1
aLine = fgetl(FID);
if ~ischar(aLine)
break;
end
i = i + 1;
Data{i} = sscanf(aLine, '%f');
end
fclose(FID);
Data = Data(1:i);
0 个评论
Walter Roberson
2011-10-25
There is no built-in function that will do this for you.
If you replace the empty line with NaN or inf or -inf then when it reaches that point in the plot it will break the plot and skip to the next location. This will, however, not be the same as a new dataset because for a new dataset plot would automatically use a new color but in the case of the break values it is constrained to continue using the same color and same marker.
If you do want the behavior I describe, then you can hack with one of the built-in functions:
fid = fopen('YourTextFile.txt','rt');
result = textscan(fid, '%f\n', 'HeaderLines', NumberOfHeaderLinesToSkip, 'Whitespace','');
fclose(fid);
data = result{1};
where NumberOfHeaderLinesToSkip is the appropriate number.
Note: the \n at the end of the format string, and changing WhiteSpace, is required to get this to work automagically!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Large Files and Big Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!