Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Given is a list with x, y, z coordinates:

{{100, 94, -1.112}, {100.05, 94, -1.112}, {100.1, 94, -0.982}, ..., {100, 94.25, -1.112}, {100.05, 94.25, -0.855}, {100.1, 94.25, -0.728}, ..., {139.95, 114.75, 1.184},{140, 114.75, 1.184}}

I want to split this list into files with y = constant, y should moreover form the name of the new file (see the code below) and only the (x, z) values should be written into the file.

Getting the name for the first file I use this code:

liste = ReadList[inffile, {Number, Number, Number}];
y = liste[[All, 2]];
fil = IntegerString[IntegerPart[First[y]*100], 10, 5];
newfile = ToString[fil] <> ".dat";
wfile = OpenWrite[newfile, FormatType -> TraditionalForm];

Which is the best way to extract now all (x,y,z) with the same y (y = 94) from this list, to write all of them into the new file, and to continue with the next new file with the next y-value (y = 94.25)? Thanks a lot

share|improve this question
add comment

1 Answer

up vote 7 down vote accepted

GatherBy is a very convenient function you should look into (Performing operations on subgroups of data).

data = {{100, 94, -1.112}, {100.05, 94, -1.112}, {100.1, 
   94, -0.982}, {100, 94.25, -1.112}, {100.05, 94.25, -0.855}, {100.1,
   94.25, -0.728}, {139.95, 114.75, 1.184}, {140, 114.75, 1.184}};

Here you group all the cases that have the identical second value:

groups = GatherBy[data, #[[2]] &];

And, then you can just select each group:

groups[[1]]
(* {{100, 94, -1.112}, {100.05, 94, -1.112}, {100.1, 94, -0.982}} *)

To export x,z values into different files named after y value:

Table[Export[IntegerString[IntegerPart[groups[[i, 1, 2]]*100], 10, 5] <> ".dat", 
  groups[[i, All, {1, 3}]], "TSV"], {i, Length[groups]}]

or, more concisely, as suggested by Verde:

Export[IntegerString[IntegerPart[#[[1, 2]]*100], 10, 5] <> 
    ".dat", #[[All, {1, 3}]], "TSV"] & /@ groups
share|improve this answer
    
Export["Group" <> ToString[#[[1, 2]]] <> ".txt", #[[All, {1, 3}]], "TSV"] & /@ groups –  belisarius Aug 7 '12 at 16:53
    
Hi VLC, thanks a lot!!! Also for the link. This is exactly what I was looking for. I did so much crazy programming in the last hours... –  Harald Aug 7 '12 at 16:57
    
@Verde good point. –  VLC Aug 7 '12 at 17:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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