icypy
icypy

Reputation: 3202

MATLAB error message "This statement is not inside any function."

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

Upvotes: 7

Views: 20669

Answers (1)

user3717023
user3717023

Reputation:

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).

Upvotes: 10

Related Questions