7
$\begingroup$

Is it possible to have multiple outputs from a single function?

For example:

In[1]:= x+1
        x+2
Out[1]= 1+x
Out[2]= 2+x

has multiple outputs, how can I acheive that in a function?

I tried

In[3]:= f[x_]:=Module[{},
x+1
x+2
]
In[4]:= f[2]
Out[4]= 6

which doesn't work.

$\endgroup$
  • 1
    $\begingroup$ The only way I can think of is to use NotebookWrite. $\endgroup$ – Chip Hurst Nov 22 '13 at 3:27
7
$\begingroup$

I have found this solution:

In[1]:= f[x_] := CellPrint[{
                    Cell[BoxData[ToBoxes[x + 1]], "Output"],
                    Cell[BoxData[ToBoxes[x + 2]], "Output"]}]

In[2]:= f[2]

3
4

I was originally trying to achieve something like this:

f[data_] :=
  CellPrint[{
    Cell["Data", "Subsection"],
    Cell[BoxData[ToBoxes[ListLinePlot[data]]], "Output"],
    Cell["Fourier transform", "Subsection"],
    Cell[BoxData[ToBoxes[ListLinePlot[Abs[Fourier[data]]^2]]], "Output"]
    }]

which will generate two subsections

f[RandomReal[1, 200]]

enter image description here

$\endgroup$
  • $\begingroup$ There is no reason to use Module in the definition of f; f[x_] := CellPrint[{Cell[BoxData[ToBoxes[x + 1]], "Output"], Cell[BoxData[ToBoxes[x + 2]], "Output"]}] works just as well $\endgroup$ – m_goldberg Nov 22 '13 at 4:39
  • $\begingroup$ @m_goldberg yes you are right, let me correct that. Thanks for pointing it out :) $\endgroup$ – xslittlegrass Nov 22 '13 at 16:15
3
$\begingroup$

May be you are looking for :

f[x_] := CellPrint /@ (ExpressionCell[#, "Output"] & /@ {x + 1 , x + 2}); ?

ExpressionCell[...] replaces the complicated structure Cell[BoxData[ToBoxes[...]]]

$\endgroup$
1
$\begingroup$
Clear[f];
f[x_] := Module[{},
  Column[{x + 1, x + 2}]
  ]

Then

f[1]

(* 2 3 *)

$\endgroup$
  • $\begingroup$ But it is one output cell, OP wants each result in different cell. $\endgroup$ – Kuba Nov 22 '13 at 8:34
  • $\begingroup$ @Kuba I would say that from his question I did not unequivocally see that. I have at least two interpretations of the question. $\endgroup$ – Alexei Boulbitch Nov 22 '13 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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