2

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

Mika Ike
  • 3,241
  • 1
  • 23
  • 38

1 Answers1

3

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.

RobertNathaniel
  • 790
  • 4
  • 12
  • Thank you. It works. But now I want to go back to the past. I deleted the package, now whenever I open Mathematica, it gives an error about the deleted package. How to achieve package to be non-autoloaded again. – HD239 Dec 13 '21 at 11:06
  • You need to remove the package from the list of initialization contexts. If you have no other packages you want to autoload, just do;

    InitializationValue[$InitializationContexts] = {}

    Otherwise just list the packages that you DO want to be autoloaded.

    – RobertNathaniel Dec 14 '21 at 13:57