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
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityI 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 TypeSystem
AnyType. >>`
$\endgroup$
– jset
Jun 15 '16 at 11:39
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.
e
with*^
andi
withI
, and thenImportString
it. $\endgroup$ – Oleksandr R. Jun 15 '16 at 13:46