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.

3
  • Its not a duplicate, that question asks something different and is actually a lot more vague than what I'm asking here. Commented Mar 22, 2011 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. Commented Mar 22, 2011 at 16:48
  • Yeah so close that one not this one Commented Mar 22, 2011 at 17:19

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Thanks, I replaced must with should.
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

1 Comment

Stored in myMath.m. So you're saying any other function other than the "primary" function is considered a subfunction

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.