Import .csv with missing delimiters and values

14 views (last 30 days)
I am trying to import some (generated) .csv files into MATLAB. Unfortunately, some of the files have rows with blank entries AND missing delimiters (in my case a semi-colon is the delimiter). This means when I am trying to import the .csv file using readtable, the dimensions of the table are wrong, i.e. MATLAB is confused and packs the data in cells. I need the table to be the right size so that I can use it later on.
An example .csv file would look like this:
date;time;var1;var2;var3
02.06.21;15:00:00;1;2;3
02.06.21;16:00:00;4
02.06.21;17:00:00;5;6;7
As you can see, there are missing values in the second row AND the delimiters are also missing. Is there any way I can import the .csv file so that the table has the width of the widest row, and that the needed delimiters would be added automatically (I don't really care about the value that would be put in these spaces but I need the format).
Thanks for any help in advance!

Accepted Answer

Cris LaPierre
Cris LaPierre on 2 Jun 2021
Edited: Cris LaPierre on 4 Apr 2022
I am able to use readtable to load the data you have shared without any trouble. It does not put the data into a cell, and it fills the missing columns with NaN.
% No options set. Year is wrong, but table width is correct.
attempt1 = readtable("HH_file.csv")
attempt1 = 3×5 table
date time var1 var2 var3 __________ ________ ____ ____ ____ 02.06.0021 15:00:00 1 2 3 02.06.0021 16:00:00 4 NaN NaN 02.06.0021 17:00:00 5 6 7
% Now add some formatting to date and time
opts = detectImportOptions("HH_file.csv");
opts = setvartype(opts,"date",'datetime');
opts = setvaropts(opts,"date",'InputFormat','dd.MM.yy');
opts = setvartype(opts,"time",'duration');
opts = setvaropts(opts,"time",'InputFormat','hh:mm:ss');
attempt2 = readtable("HH_file.csv",opts)
attempt2 = 3×5 table
date time var1 var2 var3 ________ ________ ____ ____ ____ 02.06.21 15:00:00 1 2 3 02.06.21 16:00:00 4 NaN NaN 02.06.21 17:00:00 5 6 7
I didn't have R2020a installed, but I did test this code in R2019b. It worked there.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!