7

I am trying to define a simple function and then call it:

   function p=MyExp(N);
      p=[ 1 ]; % 0th order polynomial. 
      for k=1:N
         pk=1/(factorial(k));
         p=[pk,1];
      end
   end


   poly3=MyExp(3);
   disp (poly3)

MATLAB is returning a message: Error: File: matlab_labIII_3_I.m Line: 10 Column: 1 This statement is not inside any function. (It follows the END that terminates the definition of the function "MyExp".)

This script works well on OCTAVE!

Thanks

2
  • What is matlab_labIII_3_I.m and how does it relate to MyExp? Commented Dec 7, 2014 at 22:45
  • matlab_labIII_3_I.m is the file name that I am executing. Commented Dec 7, 2014 at 23:10

1 Answer 1

10

If you use functions in a Matlab script, you are expected to have all code inside of function(s), of which there can be more than one. Similar products (Octave and Scilab) do not have this restriction.

There's an easy way out with minimal change of code: wrap the non-function code into a function, and invoke that. The main function should appear first in the script.

function MyProgram()
   poly3=MyExp(3);
   disp (poly3)
end 

function p=MyExp(N);
      p=[ 1 ]; % 0th order polynomial. 
      for k=1:N
         pk=1/(factorial(k));
         p=[pk,1];
      end
end

Also, when you use functions, Matlab expects the name of your file to match the name of the function to be called. So, the file should be named MyProgram.m (or whatever your main function is named).

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

6 Comments

So you are saying that each defined function needs to live in its own script?
No, you can have two or more functions in the script. I said that as soon as you have a function there, everything must be within some function.
Also, I should have said that the main function is expected to be the first one.
This is very non intuitive as I come from the Python world, but I have a math assignment in MATLAB. This MATLAB constrain is very disappointing. I like defining functions at the beginning of my script and use them later on, in the same script (as I do in python). Thanks for the fast and informative answer.
I find it nonintuitive and disappointing too. :) Matlab has a long line of development and sticks to some conventions from the 80s. Many users split their task into a bunch of .m files holding one function each...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.