4
$\begingroup$

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?

$\endgroup$
1
  • 1
    $\begingroup$ IIRC, ReadList will parse the numbers correctly, though I don't know if it will read in the correct format. $\endgroup$
    – Daniel
    Aug 4, 2015 at 23:34

2 Answers 2

7
$\begingroup$

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

u = Import["file.dat"]

Head /@ Flatten[u]

$\ $ {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}}

$\endgroup$
7
$\begingroup$

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}}
$\endgroup$
2
  • $\begingroup$ On can use Map[Interpreter["ComplexNumber"], u, {2}] for u = Import["file.dat"], if the file is formated as shown in the question. $\endgroup$
    – Karsten7
    Aug 4, 2015 at 22:13
  • $\begingroup$ I don't have the built in function Interpreter... I'm using Mathematica 9. $\endgroup$
    – David
    Aug 4, 2015 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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