2

I did some look up , found a few answers but none pretty clear or certain.

I'm just wondering, is it possible to define MatLab functions locally within scripts (m-file) ?

Because sometimes i just want a little function that I won't be using for any other script, so I don't want to create a new file for it. for the ease of handling them.

0

2 Answers 2

7

In a script you can only define anonymous functions. These functions are limited to a single statement. For example:

f = @(x,y) max(x,y).^2;

f is a function handle, which is used to call, or to refer to, that function:

>> x = [1 2];
>> y = [3 0];
>> f(x,y)
ans =
     9     4
Sign up to request clarification or add additional context in comments.

4 Comments

oh that's a shame. still if this is the best matlab has to offer for that matter, I appreciate the answer !
Anyway, creating a function file in the same folder as your script is not so cumbersome, is it?
@LuisMendo, sometimes it is. ;-) I have a folder full of m-files that I wrote when answering questions on SO, usually named after the person asking the question. In many cases I would like to define functions to call in the script, but distributing one answer over several files makes the folder a total mess.
@A.Donda You are right. That's a good example when packing functions on the same file would be more convenient
1

Do you mean nested functions?

Example from Matlab:

function parent
disp('This is the parent function')
nestedfx

   function nestedfx
      disp('This is the nested function')
   end

end

2 Comments

I don't mena a function inside a function, but rather a function defined within a script. Like in the middle of your code, in a file that is not a function definition file.
oh i see. Then seems anonymous functions as Luis's answer is the best approach.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.