Tosmai
Tosmai

Reputation: 60

Declaring variables before declaring a function

Suppose I want to declare some variables then declare a function:

x = 2;
function y = function(x)
    y = (x^2)+1;
end
y = function(x);
disp(y)

Matlab returns the error "Function keyword use is invalid here..."

Why can't I declare variables or write any text before declaring a function? Is there good reason or is it a quirk?

EDIT: To clarify, I do know how to get around this problem (but thanks for the suggestions nonetheless) but I suppose I'm asking why the Matlab team made this decision. By making a function declaration the first line of a file, does it have implications for memory management, or something?

Upvotes: 0

Views: 525

Answers (3)

Steve Osborne
Steve Osborne

Reputation: 680

Others have given good info about nested functions and such.

But the reason for the error you get is that "function" is a reserved word in Matlab. You cannot have a function with this name.

function y = my_function(x)
    y = (x^2)+1;
end

And stick it in another file called my_function.m

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112759

  1. If a function is defined in a file, there are two possibilities:

    • The main function of that file. Then the file must begin with the function declaration: in your example, function y = fun(x). I'm using fun as the function's name. I don't think function can be used as a function's name.

      See here for more details.

    • A nested function. In this case, the function declaration and definition can be within another function of the preceding case.

      See here for more details.

    As you can see, in either case the file begins with a function declaration (namely that of the main function).

  2. The function can also be defined as an anonymous function. Then no declaration is needed, and the function can be defined anywhere. But there's a restriction: the function can contain only a single statement (so it cannot define internal variables other than the output). Therefore this method can only be used for simple functions.

    In your example, the function could be defined anonymously as fun = @(x) x^2+1.

    See here for more details.

Upvotes: 1

user2987828
user2987828

Reputation: 1137

The REPL prompt of Scala can have a function defined after a variable. So this is a choice (a quirk if you want) from Matlab's inner internals.

Upvotes: 1

Related Questions