0
$\begingroup$

I have a .txt file which have following form

Name1 number1 number2 number3 Name2 number4 number5 number6 Name3 number6 number8 number9

I want to import these data as following matrix

new={{number1,number2,number3,number4,number5,number6,number7,number8,number9}}

namely a 1x9 matrix. When I try this code

new = Part[Import["path\filename.txt", "Table"], Range[1, 3],2 ;; 4]

I get a 3x3 matrix as

new={{number1,number2,number3},{number4,number5,number6},{number7,number8,number9}}

due to using the Part command. How can I build a 1x9 matrix where all numbers are placed in one row by importing data from the file or convert the 3x3 matrix obtained from above code to a 1x9 matrix?

$\endgroup$
11
  • $\begingroup$ Apply Flatten to new. $\endgroup$ Commented Apr 9, 2018 at 9:42
  • $\begingroup$ @Henrik Schumacher Thanks, but this command give me a 9x1 matrix rather than 1x9 one. Do you know a way which produces a 1x9 matrix by importing data from the file directly? $\endgroup$
    – Wisdom
    Commented Apr 9, 2018 at 12:53
  • $\begingroup$ Well, the matrix is stored as $3 \times 3$ matrix, so we have to convert it. Fasted way to obtain a $1 \times 9$ matrix might be ArrayReshape[new, {1, Times @@ Dimensions[new]}]. $\endgroup$ Commented Apr 9, 2018 at 13:04
  • $\begingroup$ @Henrik Schumacher That's right! it works perfectly. Thanks. Can you explain about your code a bit? $\endgroup$
    – Wisdom
    Commented Apr 9, 2018 at 13:31
  • $\begingroup$ Well, have a look into the documentation of ArrayReshape. Times @@ Dimensions[new] just computes $3 \cdot 3 = 9$ in a way that also works for other matrix sized of new. $\endgroup$ Commented Apr 9, 2018 at 13:33

1 Answer 1

1
$\begingroup$

Just for completeness:

With[{new = Import["path\filename.txt", "Table"]},
  ArrayReshape[new, {1, Times @@ Dimensions[new]}
]
$\endgroup$

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.