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.

During rather long computation I have intermediate steps Printed with useful information which should be collected for possible use in future inside of the evaluation Notebook. When the computation is finished the final results are printed. But there are hundreds of intermediate Prints which fill the screen and contain supporting information which is interesting to see during computation but impede reading the final results. I wish to have an ability to collapse the intermediate prints in a CellGroup.

Here is an example from the Documentation page for EvaluationMonitor:

FindRoot[x^2 - 2, {x, 1}, 
 EvaluationMonitor :> Print["x = ", x " x^2 - 2 =", x^2 - 2]]

After evaluation of the above we get intermediate results in one collapsable CellGroup (note the collapsed cell group selected on the right):

screenshot

My problem is that my computation involves several cycles with intermediate evaluations and I am forced to Print the final results after a cycle is finished. So all the prints by default belong to one cell group. It can be simulated as follows:

Do[Print@FindRoot[x^a - 2, {x, 1}, 
   EvaluationMonitor :> Print["x = ", x , ", x^", a, " - 2 = ", x^a - 2]], {a, 1, 3}]

How is it possible to have intermediate prints grouped together and collapsable?

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

Instead of Print one could use CellPrint with ExpressionCell and get the desired behavior (intermediate cells are collapsed by hands):

Do[CellPrint@
  ExpressionCell[
   FindRoot[x^a - 2, {x, 1}, 
    EvaluationMonitor :> 
     Print["x = ", x, ", x^", a, " - 2 = ", x^a - 2]], "Output"], {a, 
  1, 3}]

screenshot

share|improve this answer
1  
This is good, but it would be better with EvaluationMonitor :> Print["x = ", x , ", x^", a, " - 2 = ", x^a - 2]. With this change, one can see what the actual exponent of x is. –  m_goldberg May 3 at 21:00
    
@m_goldberg Thanks, I have edited my answer accordingly. –  Alexey Popkov May 3 at 21:11
1  
Also, your solution has the drawback that the three results are not put into the output history. It is not possible to retrieve them later with Out. Because of this I think you should consider another modification -- changing FindRoot[...] to rule[a] = FindRoot[...] -- allowing latter access to the results of FindRoot as rule[1], rule[2], rule[3]. –  m_goldberg May 3 at 21:56
    
@m_goldberg I see your point, but this question is about output formatting. You suggest some kind of memoization which is useful but not strictly related to the question. –  Alexey Popkov May 3 at 22: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.