3
$\begingroup$

I just started using Mathematica. I got some output in a txt file from some computations in Pari/GP which looks like this:

$$ [1,2,3,4; 5,6,7,8]$$

Here I want to import the data into Mathematica and get a table. The semicolons indicate a new row and commas separate each entry on a row. I cannot figure out how to do this.

$\endgroup$

2 Answers 2

6
$\begingroup$
filename = "C:/data.txt";
First@ReadList[filename, Record, RecordSeparators -> {{"["}, {"]"}}] //
   StringSplit[#, ";"] & // 
 Map[Interpreter[DelimitedSequence["Number"]]]

{{1, 2, 3, 4}, {5, 6, 7, 8}}

$\endgroup$
4
  • $\begingroup$ This works completely fine when the original matrix has dimensions like 3244 $\times$ 7. But for a row vector, as in the text file being [1,2,3,4], your code gives something like {{1,2,3,4}} with an extra brace, this is not interpreted as a matrix in Mathematica. $\endgroup$ Jul 25, 2023 at 12:32
  • 2
    $\begingroup$ @AdityaGhosh {{1,2,3,4}} is the Matrix in Mathematica. {{1, 2, 3, 4}} // MatrixQ is True. By the way, there not row vector or column vector in vector spaces. row or column only in Matrix. $\endgroup$
    – cvgmt
    Jul 25, 2023 at 12:38
  • $\begingroup$ Evaluate: {Dimensions@#, MatrixQ@#} &@{{1, 2, 3, 4}}. Thanks for the comment by @cvgmt. $\endgroup$
    – Syed
    Jul 25, 2023 at 12:38
  • $\begingroup$ I think using Catenate solves the issue for me, as it removes that extra brace $\endgroup$ Jul 25, 2023 at 12:40
4
$\begingroup$

First we import the data as a string:

filename="d:/tmp/test.dat";
tmp=Import[filename][[1, 1]];

Then we adjust the syntax:

tmp= StringReplace[tmp , {"[" -> "{{", "]" -> "}}", ";" -> "},{"}] 

Finally we convert the string into an expression and display it:

ToExpression[tmp] // TableForm

enter image description here

$\endgroup$
4
  • $\begingroup$ Thanks, that solves it. But what's the utility of [[1, 1]] in the second line? $\endgroup$ Jul 25, 2023 at 11:44
  • 1
    $\begingroup$ This gets rid of unwanted braces. $\endgroup$ Jul 25, 2023 at 11:47
  • $\begingroup$ Actually, without [[1, 1]], I'm having this issue when I'm using this code on text like [0;1;2;3;4]. As you said, it's giving a lot of unwanted brackets. But including [[1, 1]] gives the errors: Part specification is longer than depth of object and String or list of strings expected at position 1 in StringReplace. Can you maybe explain how the argument [[1, 1]] works? $\endgroup$ Jul 25, 2023 at 12:04
  • $\begingroup$ Check what your file contains. test.dat contains: [1,2,3,4;5,6,7,8]. The import command should give a string like: {{"[1,2,3,4;5,6,7,8]"}} where the double quotes are not displayed by MMA. [[1,1,]] gets ride of the double braces. $\endgroup$ Jul 25, 2023 at 12:47

Your Answer

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

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