1

Imagine I have 2 notebooks with the following contents:

Notebook 1: "notebook1.nb"

a1 = 1;

f1[x_, y_, z_] := x + y + z;

Print[f2[2, 1]];

Notebook 2: "notebook2.nb"

a2 = 2;

f2[x_, y_] := x - y;

Print[f1[1, 2, 3]];

Print[a1 + a2];

What do I have to do that the notebooks can share variables and functions with each other?

mrz
  • 11,686
  • 2
  • 25
  • 81
  • 3
    Notebooks do share all definitions by default. Make sure that Evaluation -> Notebook's Kernel is Local and Notebook's Default Context is Global. These are the defaults, and it should be like this unless you changed them yourself. – Szabolcs Dec 15 '16 at 12:09
  • But what is if I would only open notebook1.nb and not notebook2.nb. Is it possible to import/include somehow the content and definitions, like in other languages. – mrz Dec 15 '16 at 12:13
  • 2
    I think that is a completely different question ... Use packages, not notebooks. Notebooks are for interactive work: they are meant to be opened and evaluated manually. Packages are meant to be loaded using a command (i.e. programmatically). "Package" here means: put everything into a plain text file with an .m (or .wl) extension and load it using Get. – Szabolcs Dec 15 '16 at 12:15
  • @Szabolcs: Can you show a simple example how to start? – mrz Dec 15 '16 at 12:18
  • 1
    There isn't anything to show really ... enter those commands into a text file, not a notebook. Save the file as something.m. To evaluate all expressions in the file, use Get["something.m"] (you may need to specify the full path). – Szabolcs Dec 15 '16 at 12:21
  • 1
    If you want to use the front end as you editor, start with File -> New -> Package (and not File -> New -> Notebook) – Szabolcs Dec 15 '16 at 12:21
  • 1
    Once you are comfortable with doing this, take a look here as well: http://mathematica.stackexchange.com/q/1369/12 Also, if you strongly prefer notebooks, it is possible to evaluate them programmatically using NotebookEvaluate (since version 10.0, I think). But I still maintain that plain text .m files are much better for this purpose. – Szabolcs Dec 15 '16 at 12:23
  • Thank you very much. This Infos helps me a lot. – mrz Dec 15 '16 at 12:34
  • Try doing evaluations without Print. You will find that you don't need Print – m_goldberg Dec 15 '16 at 17:04

0 Answers0