Importing text file data?

조회 수: 1 (최근 30일)
Christopher
Christopher 2013년 11월 14일
편집: Cedric 2013년 11월 14일
Hello everyone,
I have written a function that imports .txt files and removes the 5 header lines. Right now the function only reads .txt files with 6 columns of data. I am trying to make this file more robust, so that it can read .txt files with any number of data columns up to say 12. I am not sure how to appproach this and was looking for some help in doing so. Here is my function:
function[data]=Load_Data(filename,strain_command_data)
FID=fopen(filename);
data=textscan(FID,%f%f%f%f%f%f','HeaderLines',5,'CollectOutput',1);
fclose(FID);
data=data{1}
rows_remove=find(data(:,strain_command_data)==0);
if (~isempty(rows_remove)),
data=data(1:rows_remove(1)-1,:);
end
end
Any help would be great.
  댓글 수: 1
per isakson
per isakson 2013년 11월 14일
Did you search the File Exchange for ideas?

댓글을 달려면 로그인하십시오.

채택된 답변

Cedric
Cedric 2013년 11월 14일
편집: Cedric 2013년 11월 14일
What part are you not able to make more versatile?
If you know a priori the number of columns, you can make the following changes
function data = Load_Data( filename, strain_command_data, nCol )
if nargin < 3
nCol = 5 ; % Default.
end
formatSpec = repmat( '%f', 1, nCol ) ;
FID = fopen( filename ) ;
data = textscan( FID, formatSpec, 'HeaderLines', 5, 'CollectOutput', 1 ) ;
.. etc.
end
If you don't know a priori the number of lines, you could determine it based on one line of the header. If the file had the following content
Header line 1..
Header line 2..
dataID time x y
1 120 8.7 9.1
you could determine that there are 4 columns based on the 3rd line of the header which contains column labels..
function data = Load_Data( filename, strain_command_data )
fid = fopen( filename, 'r' ) ;
fgetl( fid ) ; % Skip line 1.
fgetl( fid ) ; % Skip line 2.
colLabels = fgetl( fid ) ;
nCol = numel( regexp( colLabels, '\s+' )) + 1 ;
formatSpec = repmat( '%f', 1, nCol ) ;
data = textscan( fid, formatSpec, 'CollectOutput', 1 ) ;
.. etc.
end

추가 답변 (0개)

카테고리

Help CenterFile 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!

Translated by