3

Possible Duplicate:
In MATLAB, can I have a script and a function definition in the same file?

Can I have MATLAB script code and function code in the same file?

%% SAVED IN FILE myfunc.m (otherwise fail)
function [out1] = myfunc( x )
out1 = sqrt( 1 + (cos(x))^2 );
end

%%
%OTHER CRAP
y = 1:10
% use myfunc

It doesn't seem to work, even with the end keyword there. Is this type of thing allowed or do I always need to have EACH function in its own properly named file?

I'm sure I saw functions and code that uses those functions in the same file a couple years ago.

Community
  • 1
  • 1
bobobobo
  • 64,917
  • 62
  • 258
  • 363
  • Its not a duplicate, that question asks something different and is actually a lot more vague than what I'm asking here. – bobobobo Mar 22 '11 at 16:37
  • Although the other question is not very well written/formatted, both questions ask the same thing: if you can combine a script and a function definition in the same file. – gnovice Mar 22 '11 at 16:48
  • Yeah so close that one not this one – bobobobo Mar 22 '11 at 17:19

2 Answers2

9

If m-code has a function in it, all the code must be encapsulated by functions. The name of the entry-point function should match the filename. If you think about it, this makes sense because it favors code re-use.

You can try this:

filename: myScript.m

function [] = myScript()
 y = 1:10;
 out1 = myfunc(y);
end

function [out1] = myfunc( x )
 out1 = sqrt( 1 + (cos(x))^2 );
end

Then you can either hit F5, or from the matlab command prompt type myScript

rossb83
  • 1,694
  • 4
  • 21
  • 40
  • 1
    The entry-point function _should_ match the filename, but the language does not enforce it. If it differs, Matlab will use the filename as the name of the function, ignoring the "function" line. It's a warning in mlint. – Andrew Janke Mar 22 '11 at 18:09
  • Thanks, I replaced must with should. – rossb83 Mar 22 '11 at 20:11
3

rossb83's answer is correct, and just to extend that, you should know that functions can have subfunctions:

function sum = function myMath(a, b)
    foo = a + b;
    bar = mySubFunc(foo);
end

function bar = mySubFunc(foo)
    bar = foo^2;
end
Community
  • 1
  • 1
eykanal
  • 26,437
  • 19
  • 82
  • 113
  • Stored in `myMath.m`. So you're saying any other function other than the "primary" function is considered a subfunction – bobobobo Mar 22 '11 at 17:23