필터 지우기
필터 지우기

How to extract specific arrays out of a CSV file

조회 수: 1 (최근 30일)
JVM
JVM 2017년 1월 16일
답변: Walter Roberson 2017년 1월 19일
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.

답변 (2개)

Wilson A N
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:

Walter Roberson
Walter Roberson 2017년 1월 19일
Consider using readtable() if you are using R2013b or later.

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by