Reputation: 5690
Sorry this is such a basic question, but I can't find a straight answer and it doesn't seem to have been answered on here before (perhaps because it is so basic?!)
I'm trying to call a M function from within another M file. The function I am calling is a primary function and has no inputs or outputs: it is simply some lines of code that I'd like to insert many times in my main M-file.
The function is called
function generateGrating
and resides in the file generateGrating.m. The main function is called
function project
and resides in the file project.m. As you can see, there is no input or output in either. They simply run their routines.
I have tried the following to attempt to call the function, with no luck:
generateGrating()
generateGrating
generateGrating.m()
generateGrating.m
generateGrating();
generateGrating;
generateGrating.m();
generateGrating.m;
Any help would be appreciated! It seems that the answer must be so basic that I can't find it anywhere :(
Upvotes: 0
Views: 29917
Reputation: 5467
It should just be generateGrating
. The files generateGrating.m
and project.m
need to both be in directories that are included in the Matlab path. The easiest way to accomplish that is to have them both be in the same directory and to run with that directory as your working directory. The simplest thing to do is to open project.m
and hit F5 to run it, and click the "Change directory" button if it pops up.
NOTE
If generateGrating
is populating some variables (it sounds like that's what you're doing), then DON'T make generateGrating
a function
. Otherwise any variables that are set in generateGrating.m
will only be in scope within that function. For example:
% generateGrating.m
function generateGrating()
x = 42;
% project.m
x = 1;
generateGrating
disp(x)
Will display x = 1 because x is only 42 within the scope of the function generateGrating
. But changing generateGrating.m
to
% generateGrating.m
x = 42;
And running project
again will display x = 42;
Upvotes: 1
Reputation: 16035
I think that you want to use a script, not a function.
A script is a .m file without the keyword function at the beginning.
So for instance, i fI have two files:
sub.m:
b=b+1;
main.m:
function main
b=1;
b
sub;
b
sub;
b
I get the answer:
b=1
b=2
b=3
If I change sub.m to make it a function:
sub.m:
function sub
b=b+1;
The variable b inside sub is now from a different scope than b in main.m So I get the answer:
b=1
b=1
b=1
Upvotes: 1