# Reading from a file: complex number with small imaginary part

I'm trying to read a matrix from the next file:

1+1e-18i 24
42 23.43e-23i


using u=Import["file.dat","Table"]; and then find, for example, the trace: Tr[u] but this give me 1+1e-23i + 1+23.43e-23i. Also, Chop don't work.

How obtain the correct representation of the matrix in the file?

• IIRC, ReadList will parse the numbers correctly, though I don't know if it will read in the correct format. Aug 4 '15 at 23:34

Not all parts of your file are recognized as numeric data during the Import.

u = Import["file.dat"]



$\$ {String, Integer, Integer, String}

You can convert it for example with

SetAttributes[stringToNumber, Listable];
stringToNumber[s_String] := ToExpression[StringReplace[s, {"e" -> " 10^", "i" -> " I"}]];
stringToNumber[s_] := s;

u2 = stringToNumber@u


$\$ {{1 + I/1000000000000000000, 24}, {42, 0. + 2.343*10^-22 I}}

Now

Chop[N@u2]


$\$ {{1., 24.}, {42., 0}}

One possibility: try this (you can use Import on your file instead):

lines = ImportString[
"1+1e-18i 24
42 23.43e-23i",
"Lines"]


Then:

result = Map[StringSplit, lines]


And:

Map[Interpreter["ComplexNumber"], result, {2}]


This gives:

 {{1. + 1.*^-18 I, 24}, {42, 0. + 2.343*^-22 I}}

• On can use Map[Interpreter["ComplexNumber"], u, {2}] for u = Import["file.dat"], if the file is formated as shown in the question. Aug 4 '15 at 22:13
• I don't have the built in function Interpreter... I'm using Mathematica 9. Aug 4 '15 at 22:51