Calling functions from inside (Matlab) code sections

873 views Asked by At

I have a massive script consisting of many code sections that I run independently of each other. For some of these code sections, there is a lot of repeating code, and so I wanted to define a function that I can call multiple times from a given code section. However, I am either getting the error "Function definitions are not permitted in this context.", or, once the code execution reaches the function call, it says the function is not defined.

So it seems that Matlab (2016b) does not accept functions to be defined within code sections, or I am doing something else that's wrong.

What I tried:

  • define the entire script as a function, named exactly as the name of the containing .m file, and with a corresponding 'end' on the very last line

  • define the function containing my repeating code either at the end of the code section for which it is relevant

  • .. or at the end of the file (before the top-most function's own 'end')

  • .. or at the end of the file (after the top-most function's own 'end')

My code organisation might be criticised, e.g. I might instead use multiple functions in my file, rather than script-style code sections. However, I would like to know whether there is a way to be able to call functions from inside code sections.

1

There are 1 answers

6
Wolfie On

You need to read the following documentation:

Notably, the second contains the relevant information:

Starting in R2016b, another option for storing functions is to include them at the end of a script file.

You say you're using R2016b, so you can define functions within scripts, but they must be at the end of the file. The documentation contains the following example of a valid script containing functions:

x = 3;
y = 2;
z = perm(x,y)

function p = perm(n,r)
    p = fact(n)*fact(n-r);
end

function f = fact(n)
    f = prod(1:n);
end