user1658920
user1658920

Reputation: 33

How to define a function for later use in Mathematica

I'm just getting started on Mathematica and trying to define a function for later use. The function is:

test[x_]:=x^2

While I don't close Mathematica, I can use the function on my notebooks but when I close it, the function disappears, I tried to save a .m file with it but It didn't work. What do I do?

Upvotes: 2

Views: 2377

Answers (2)

fujianjin6471
fujianjin6471

Reputation: 5248

Open Mathematica, create a new Notebook

test[x_]=x^2;
DumpSave["test.mx",test];

You even don't have to save the Notebook, just close Mathematica.(But remember, in this case, you lose chance to modify the function forever) Then reopen Mathematica, create a new Notebook

DumpGet["test.mx"];
test[5]
(*25*)

Upvotes: 1

latkin
latkin

Reputation: 16812

Maybe you misunderstand how to save/import. Here's the process that should work:

  • Define a function like you have above, Save As test.m (In Mathematica 8, it won't "look like" you saved it, the open notebook is still "Untitled-1", but it did save. You can verify however you like.)
  • Open a new notebook
  • Import your library like this: Import["C:\\users\\joeblow\\documents\\Mathematica Notebooks\\test.m"]
  • You should now be able to access the test function

Does this not work for you?

Upvotes: 4

Related Questions