How to extract specific arrays out of a CSV file
2 ビュー (過去 30 日間)
古いコメントを表示
Hey I have a CSV file looking something like the following
Header 1 Header 2 Header 3 Header 4
'a' 'b' 1 2
'c' 'd' 3 4
'e' 'f' 5 6
The problem is, how do I remove the first two columns if I do not know how many columns there are? E.g. there could also be another header with another set of numbers.
0 件のコメント
回答 (2 件)
Wilson A N
2017 年 1 月 19 日
Assuming all the columns with headers have valid data, you can find the number of columns by just extracting the first line and using 'strsplit' command as shown in the code given below:
% Open the file and read the first line using 'fgetl' command
file_name = '<filename>.csv';
fid = fopen(file_name);
header_line = fgetl(fid);
fclose(fid);
% Splitting the headerline when it encounters the delimiter ','
file_headers = strsplit(header_line,',');
% Now the size of the file_headers indicates the number of columns present
columnSize = length(file_headers);
In case you want to check for the columns only having numerical data you can still use 'fgetl' command for a second time, so that it returns the second line. Then use the 'strsplit' command to split the obtained string according to the delimiter. After this step you will be in a position to determine which columns have numerical data.
You can refer the links given below for more information on 'fgetl' and 'strsplit' command:
0 件のコメント
Walter Roberson
2017 年 1 月 19 日
Consider using readtable() if you are using R2013b or later.
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!