1
$\begingroup$

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

$\endgroup$
  • $\begingroup$ My preference is to read the entire file in unaltered as a string, replace e with *^ and i with I, and then ImportString it. $\endgroup$ – Oleksandr R. Jun 15 '16 at 13:46
2
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ I'm obtaining Expression -0.0000507249+2.50261*10^-18 I at position {1} should be of type TypeSystemAnyType. >>` $\endgroup$ – jset Jun 15 '16 at 11:39
  • $\begingroup$ @jset It's impossible to tell what is going wrong unless we have a dataset that triggers the problem. The code I posted works in M10.4 and M10.0. $\endgroup$ – Szabolcs Jun 15 '16 at 11:50
  • $\begingroup$ I've inserted an example file in the question text (link). I'm using mathematica 10.0 on linux $\endgroup$ – jset Jun 15 '16 at 12:49
  • $\begingroup$ @jset Just to be sure: do you have 10.0.2? If not you really should upgrade to at least 10.0.2. $\endgroup$ – Szabolcs Jun 15 '16 at 12:57
  • $\begingroup$ I know, on my personal notebook I have it, but my institution doesn't have it. Thank you $\endgroup$ – jset Jun 15 '16 at 13:07
0
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.