I'm working with MATLAB for few days and I'm having difficulties to import a CSV-file to a matrix.
My problem is that my CSV-file contains almost only Strings and some integer values, so that csvread()
doesn't work. csvread()
only gets along with integer values.
How can I store my strings in some kind of a 2-dimensional array to have free access to each element?
Here's a sample CSV for my needs:
04;abc;def;ghj;klm;;;;;
;;;;;Test;text;0xFF;;
;;;;;asdfhsdf;dsafdsag;0x0F0F;;
The main thing are the empty cells and the texts within the cells. As you see, the structure may vary.
For the case when you know how many columns of data there will be in your CSV file, one simple call to
textscan
like Amro suggests will be your best solution.However, if you don't know a priori how many columns are in your file, you can use a more general approach like I did in the following function. I first used the function
fgetl
to read each line of the file into a cell array. Then I used the functiontextscan
to parse each line into separate strings using a predefined field delimiter and treating the integer fields as strings for now (they can be converted to numeric values later). Here is the resulting code, placed in a functionread_mixed_csv
:Running this function on the sample file content from the question gives this result:
The result is a 3-by-10 cell array with one field per cell where missing fields are represented by the empty string
''
. Now you can access each cell or a combination of cells to format them as you like. For example, if you wanted to change the fields in the first column from strings to integer values, you could use the functionstr2double
as follows:Note that the empty fields results in
NaN
values.In R2013b or later you can use a table:
Here is more info.
Depending on the format of your file, importdata might work.
You can store Strings in a cell array. Type "doc cell" for more information.
If your input file has a fixed amount of columns separated by commas and you know in which columns are the strings it might be best to use the function
Note that you can specify a format where you read up to a maximum number of characters in the string or until a delimiter (comma) is found.
Use xlsread, it works just as well on .csv files as it does on .xls files. Specify that you want three outputs:
and it will give you an array containing only the numeric data (num), an array containing only the character data (char) and an array that contains all data types in the same format as the .csv layout (raw).