Octave: How to create a function file from a function?

You have an Octave function and you want to move it into a separate file.

First, you need to know that a function file can only contain ONE function and that function needs to be named just like the file.

Therefore, if your function is called myfunc, you absolutely need to move it to a file called myfunc.m, or else Octave won’t find it.

Creating the file is pretty simple: Just paste the function into the file. You must ensure that the first statement in the file is function ... (else, it will be treated as a script file, not a function file) (any number of comments and empty lines is OK though)

Example: myfunc.m:

function retval = myfunc(n)
  retval = n + 5
endfunction

After you have saved that file, you can immediately use myfunc() in Octave:

>> myfunc(3)
retval =  8
ans =  8

Octave will automatically use the updated version in case you make changes to myfunc.m