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.

m.s.
  • 16,063
  • 7
  • 53
  • 88
Pedro Braz
  • 2,261
  • 3
  • 25
  • 48

2 Answers2

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • oh that's a shame. still if this is the best matlab has to offer for that matter, I appreciate the answer ! – Pedro Braz May 27 '15 at 15:13
  • 1
    Anyway, creating a function file in the same folder as your script is not so cumbersome, is it? – Luis Mendo May 27 '15 at 15:29
  • 1
    @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 May 27 '15 at 16:25
  • @A.Donda You are right. That's a good example when packing functions on the same file would be more convenient – Luis Mendo May 27 '15 at 21:16
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
scmg
  • 1,904
  • 1
  • 15
  • 24
  • 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. – Pedro Braz May 27 '15 at 14:56
  • 1
    oh i see. Then seems anonymous functions as Luis's answer is the best approach. – scmg May 27 '15 at 15:10