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
textscanlike 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
fgetlto read each line of the file into a cell array. Then I used the functiontextscanto 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 functionstr2doubleas follows:Note that the empty fields results in
NaNvalues.