1
$\begingroup$

How to autoload a few user-def funcions?.

For example the function

emo[x_]:=Module[{a=x},If[x>0,"Happy","Sad"]]

saved in a .nb file or in a .m file

I tried creating in "c:\Program Files\Wolfram Research\Mathematica\11.3\SystemFiles\Autoload" a dir MyFuncs and a subdir MyFuncs/Kernel with init.m whose content is

Get["MyFunc`MyFunc`"]

Another test was

$Path=Join[$Path, {"e:\Users\......\Files\Mathematica11_3"}];

and then

<<MyFunc
<<MyFunc.nb
<<MyFunc.m

I´d like to load a fes user defined functions in an easy and practical way, whitout lot of complications. If it were possible from the files dir.

I was reading a lot of posts but whitout success

$\endgroup$
5
  • 2
    $\begingroup$ Try using init.m (reference.wolfram.com/language/ref/file/init.m.html) $\endgroup$ – Rolf Mertig Dec 7 '20 at 14:59
  • $\begingroup$ Also, do not modify anything inside of the installation directory. $\endgroup$ – Szabolcs Dec 7 '20 at 15:11
  • $\begingroup$ You should run your definitions and save them after into the .mx file by DumpSave["file.mx"]. After this, it can be loaded easily by Get. $\endgroup$ – Rom38 Dec 7 '20 at 15:44
  • $\begingroup$ @RolfMertig I tried with init.m in several ways, It was not helpful. $\endgroup$ – Mika Ike Dec 7 '20 at 17:03
  • 1
    $\begingroup$ It should work. Where did you put MyFunc.m ? $\endgroup$ – Simon Woods Dec 7 '20 at 20:43
1
$\begingroup$

I also found this not to be straightforward. This is the protocol I eventually adopted;

  1. Put your functions in a package e.g. myStuff.m.

BeginPackage["myStuff`]

(*functions to be exported go here*)

myFunc1::usage="explain how to use your function here if you wish"

myFunc2::usage="or this can be empty quotes"

Begin["`Private`"]

(*function definitions, including any private functions go here*)

myFunc1[x_] := Module[{a=0}, If[x>a, Happy, Sad]];

myFunc2[x_] := myPrivateFunc1@x + 1;

myPrivateFunc1[x_] := x^2;

End[]

EndPackage[]

  1. You now need to add the path to myStuff.m in a persistent manner.

    $Path = Join[$Path,{"C:\\dir1\\dirWhichHasMyStuff"}]

    InitializationValue[$Path] = $Path

  2. If you use <<myStuff` now, it should work. However, if you want it to be autoloaded, you need to add it as an initialization context.

    InitializationValue[$InitializationContexts] = {"myStuff`"}

(Obviously, if you already have other pre-existing initialization contexts, just add it to the existing list otherwise the old ones will be overwritten.)

The package will automatically be loaded next time you start a kernel.

$\endgroup$

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.