I can't find a way to properly read a csv file containing complex numbers in the following form:
-5.07248931892817e-05+2.50260543778902e-18i,-5.0723848172051e-05+2.870855441657444e-17i,...
Example file available here
SemanticImport will handle it. Specify the column types explicitly. Example with one column:
SemanticImportString[
"-5.07248931892817e-05+2.50260543778902e-18i
-5.0723848172051e-05+2.870855441657444e-17i",
{"ComplexNumber"}
]
This returns a Dataset which you can convert to a list using Normal.
Update: I can import your file without problems in M10.0.2 like this:
str = Import["~/Downloads/f2.csvNk.csv", "String"];
Normal@SemanticImportString[
StringReplace[str, "," -> "\n"], {"ComplexNumber"}]
It's good practice to create tables with few columns and many rows. In this case, use newline as a separator instead of commas. I achieve this with StringReplace.
Expression -0.0000507249+2.50261*10^-18 I at position {1} should be of type TypeSystemAnyType. >>`
– user40761
Jun 15 '16 at 11:39
Dataset::invatom: Expression -0.0000507249+2.50261*10^-18 I at position {1} should be of type TypeSystem``AnyType. >> , but I can bypass it by taking the first element of the DataSet (data=normal@Semantic... ; data[[1]]) .
– user40761
Jun 15 '16 at 13:43
SemanticImport is not fast. I am not really satisfied with Mathematica's import facilities and sometimes I resort to LibraryLink for speed. If you are using MATLAB and Mathematica together, then you can consider using the MATLink package for fast an easy data transfer, or you can use a more convenient file format such as v5 .mat files (native to MATLAB). Another choice is HDF5 but it doesn't have native support for complex numbers so it will only be convenient if you split to ReIm
– Szabolcs
Jun 16 '16 at 13:59
There is another solution, different from the one posted by @Szabolcs. It deals with string replacing and then converting to expression:
readMatlabComplex[file_] :=ToExpression[
StringSplit[
StringReplace[
ReadList[file, "String"]
, {"e" -> "*10^", "i" -> "*I"}]
, ","]]
It is about 10 times faster.
ewith*^andiwithI, and thenImportStringit. – Oleksandr R. Jun 15 '16 at 13:46