help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Placing Functions Inline to Script


From: Nicholas Jankowski
Subject: Re: Placing Functions Inline to Script
Date: Thu, 8 Jun 2017 12:31:24 -0400

On Thu, Jun 8, 2017 at 11:26 AM, Doug Stewart <address@hidden> wrote:


On Thu, Jun 8, 2017 at 10:03 AM, Fritz Sonnichsen <address@hidden> wrote:
I am a new octave user (matlab refugee) and trying to get through a few very basic problems to get going. I am trying to define functions within a script as shown in the code below. The script fails claiming it cannot find the function. The only workaround is to make the main script a function as well but this has some repercussions regarding preserving variables. Short of having separate files running around with my functions is there a way to help the script "see" the function definition?

Thanks
Fritz

%%%%%%%%%% script %%%%%%%%
maxpoint(3);

%%%%%%%% functions %%%%%%%
function maxpoint (p)
printf("point= %d",p);
endfunction

error: 'maxpoint' undefined near line 2 column 1


_______________________________________________
Help-octave mailing list
address@hidden
https://lists.gnu.org/mailman/listinfo/help-octave



1;  % this makes it a script

%%%%%%%% functions %%%%%%%
function maxpoint (p)
printf("point= %d \n",p);
endfunction

%%%%%%%%%% script %%%%%%%%
maxpoint(3)



To explain a bit:  as you know there are scripts and function files. If the first executable line in an m-file is a function declaration, Octave will treat the file as a function that can then be called as a function in other scripts or at the command line.  The general convention is one function per file. The file can have other subfunctions listed after the main fucntion that will only visible to the main function.  Multiple files really aren't a problem unless you have particular concerns.

Scripts are just lists of commands that will be executed in the order they appear in the m-file.  Octave will treat it as a script if the first line is not a function definition, hence Doug put a '1;'  as the first line. Functions can then be defined inline in the script file, but the function must be defined before it is called (hence Julien's point of having the maxpoint(3) line after the function maxpoint definition)

Note that there have been some recent changes in Matlab about handling functions in script files that may cause some of this to change in the future, however the above info should cover more of your apparent needs for now.

Nick J.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]