0
$\begingroup$

I used Mathematica to export plots of NM measurements with this code:

Do[Export["Plot" <> ToString[i] <> ".pdf", Plottable[[i]], "PDF"], {i, NM}];

It does what it should do and I found this solution often on the Internet. On the other hand, I often read that one should avoid loops.

Is there a better (more elegant) solution? (I am not looking for another solution that just works.)

$\endgroup$
2
  • 1
    $\begingroup$ "Avoid" is a rather strong word here. If your output is expected to be indexed, as in this case, then certainly you should employ a loop. Do[] is in fact eminently suitable. $\endgroup$ May 6, 2015 at 13:24
  • $\begingroup$ Nevertheless, Scan[] is sometimes helpful. $\endgroup$ May 6, 2015 at 13:26

1 Answer 1

2
$\begingroup$

Personally, in this case I think Do is acceptable.

However, an arguably more elegant way of approaching the task, where you don't need to specify the number of elements in plottable, is with MapIndexed.

MapIndexed[Export["Plot" <> ToString @@ #2 <> ".pdf", #1, "PDF"] &, plottable]

Unlike Do this returns a list of the outputs of Export, i.e. the names of the written files, which of course can be suppressed using ;.

$\endgroup$

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