How to extract specific arrays out of a CSV file
5 views (last 30 days)
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.
Wilson A N on 19 Jan 2017
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);
% 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: