1
$\begingroup$

I have several TSV lists (.txt) of something like 2000*2000 numerics (e.g. 1.8645) to import (symmetric matrices), rearrange and sort them by each row. Finally the data should be exported. The lists are imported by using Import but what I've tried so far to manipulate the lists is not working.

An simplified example for a file to import looks like this. First I have to remove the 1st row and column.

0   1   2   3   4
1   0   2   7   1
2   2   0   8   5
3   7   8   0   9
4   1   5   9   0

Afterwards the data should look like this:

0   2   7   1
2   0   8   5
7   8   0   9
1   5   9   0

Then, the data should by sorted ascending by each row:

0   1   2   7
0   2   5   8
0   7   8   9
0   1   5   9

Finally this list is exported with Export.

This is what I wrote up to now:

SetDirectory[NotebookDirectory[]];
myFileNames = Take[FileNames["*txt"]];
lineStart = 2;
lineEnd = 5;
For[c = 1, c <= Length[myFileNames], c++,
  Data = {};
  aa = myFileNames[[c]];
  myImportData = Import[aa, "TSV"];
  Data = myImportData;
  (*delete 1st row and column*)
  For[cc = 1, cc <= lineEnd - lineStart + 1, cc++,
   Delete[Data, {1, cc}];
   ];
  For[cc = 1, cc <= lineEnd - lineStart + 1, cc++,
   Delete[Data, {cc, 1}];
   ];
  (*sort the data by each column*)
  For[cc = 1, cc <= lineEnd - lineStart , cc++,
   Sort[Data {cc, 1}];
   ];
  (*transpose the matrix to achive sorted rows*)
  Transpose[Data];
  (*export the data*)
  Export[ToString[aa] <> "_output.txt", Data, "TSV"];
  ];

For some reason even Delete is not working. My idea was to sort the columns and transpose the list to achieve the sorted rows.

If you know any good tutorial or something similar I'd really appreciate a hint where to find it. Thank you for your help!

$\endgroup$

1 Answer 1

2
$\begingroup$

Try this:

names = FileNames["*.txt"];
Export[StringInsert[#, "_output", -5], 
   Sort /@ Import[#, "Table"][[2 ;;, 2 ;;]], "TSV"] & /@ names
$\endgroup$
4
  • $\begingroup$ Can you show a simple input/output ? $\endgroup$
    – Sektor
    Feb 10, 2015 at 9:51
  • $\begingroup$ I worked on the example give by the OP and I got the same output. $\endgroup$ Feb 10, 2015 at 10:25
  • $\begingroup$ Thanks alot. Even with the real data the code is working.I think I really have to improve my mathematica-skills. Do you have any suggestion how to learn to use mathematica in such way? $\endgroup$
    – Jan
    Feb 10, 2015 at 10:37
  • $\begingroup$ My pleasure to help. thanks for accepting the answer. you can find good information here: mathematica.stackexchange.com/questions/18/… and here:mathematica.stackexchange.com/questions/18393/… $\endgroup$ Feb 10, 2015 at 10:40

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.