フィルターのクリア

find number of columns on text file

8 ビュー (過去 30 日間)
Richard
Richard 2012 年 11 月 20 日
Is it possible to determine the number of columns in a text file prior to importing the data into matlab?
I can determine the number of rows as follows:
fid = fopen('myFile.txt','rt');
nLines = 0;
while (fgets(fid) ~= -1),
nLines = nLines+1;
end
fclose(fid);
However, is there a way of returning the number of columns? Some of the text files that I need to import contain several column and others contain only one column therefore I require the number of columns in a specific text file in order to use textscan. Note I cannot use importdata or dlmread as some of the files contain nans.
Amended: Consider I create two text files:
d1 = 1+(30-1).*rand(365,3);
d2 = 1+(30-1).*rand(365,1);
mkdir('C:\Matlab_Q');
filename = 'C:\Matlab_Q\ex1.txt';
fid = fopen(filename,'wt');
fprintf(fid,'%f\n',d2);
fclose(fid);
filename = 'C:\Matlab_Q\ex2.txt';
fid = fopen(filename,'wt');
fprintf(fid,'%f\t%f\t%f\n',d1');
fclose(fid);
I now wish to read the number of columns in each text file:
FNames = {'ex1','ex2'};
delimiter = '\t';
for i = 1:length(FNames);
fid = fopen(fullfile('C:\Matlab_Q',[FNames{i} '.txt']),'rt');
tLines = fgets(fid);
numCols{i} = numel(strfind(tLines,delimiter)) + 1;
fclose(fid);
end
This solution returns 1 where it should return 1 and 3. How can this be solved?

採用された回答

José-Luis
José-Luis 2012 年 11 月 20 日
編集済み: José-Luis 2012 年 11 月 20 日
delimiter = ' '; %or whatever
fid = fopen('myFile.txt','rt');
tLines = fgets(fid);
numCols = numel(strfind(tLines,delimiter)) + 1;
fclose(fid);
  3 件のコメント
José-Luis
José-Luis 2012 年 11 月 20 日
編集済み: José-Luis 2012 年 11 月 20 日
You are looking for the string '\t', not for a tab. Use instead:
delimiter = char(9); %for a tab
Or
delimiter = sprintf('\t','');
Mitchell Thayer
Mitchell Thayer 2013 年 1 月 7 日
Snagged that piece of code for use in a parsing function. Thanks!
-:- Mitchell

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLarge 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