MATLAB Answers


How can I replace [#] entries in a .Csv file so that Matlab can read the first row as variable names?

Asked by K
on 18 Nov 2014
Latest activity Commented on by K
on 18 Nov 2014
I have seven very large .Csv data files (about 3000 columns). Whoever made the file named each variable with "[0] Label1", "[1] Label2", etc, with square brackets and numbers preceding the variable names. Of course, this means that Matlab's data importer can't use the given variable names since they don't start with a letter.
To avoid having to manually type in the variable names, is there any way I can edit the .Csv file to find and replace all of the [*] values with nothing? I think I need to use textscan and strmatch, but I am not sure of the syntax to make this work, or how to just edit the file without erasing or changing the rest of it. Any help is appreciated! I also don't know whether something like csvwrite or dlmwrite is needed here.
.Csv file format is like this:
[0] Label 1,[1] Label 2, [2] Label 3, ...


Hi again,
So I was able to write a new header line using code found on this Answers site, and now I have a header line that has variables names like "D0Label1" which should be read in just fine. But when I try to use the importer tool, it still leaves that variable names as "VarName1" etc. Any ideas?
If you can't use readtable() like I suggested, then attach your original csvfile with the paper clip icon.

Sign in to comment.

2 Answers

Answer by Star Strider
on 18 Nov 2014

There are a number of options. If it’s an Excel file, use xlsread. Otherwise, if all the labels are on one row, use textscan with 'HeaderLines',1 to skip them.

  1 Comment

No, I don't want to skip them, I want to edit them. It's not an Excel file, it's .csv, and if I try to go through Excel, it is too large to easily get back.

Sign in to comment.

Answer by Image Analyst
on 18 Nov 2014

t = readtable('yourfile.csv')
It tries to "fix up" the column headers into valid variable names. Tables are only in R2013b and later.

  1 Comment

Ok, that kiiind of works, now I have all the data in a ginormous table. I'm not very familiar with tables, so I'll see if I can work with that. Thanks, K

Sign in to comment.