user2609410
user2609410

Reputation: 319

Matlab: Calling a function of a .m file from another .m file

I have two files in the same directory. Say FolderX/A.m and FolderX/B.m. In A.m, I have a function defined as function [Out] = fun(AA, Cal)

I tried appending the global keyword before the function but that throws syntax error

function [Out] = fun(AA, Cal)

Upvotes: 0

Views: 4537

Answers (2)

Mefitico
Mefitico

Reputation: 1116

In Matlab, the global keyword applies only to variables.

If you want a function or script in FolderX to be accessible from other functions or scripts, just ensure that FolderX is in Matlab's path. This can be done either by being on this folder or with addpath.

Note that your functions should have the same name as the file name. And you should avoid having scripts and function files with the same name within Matlab's path.

Hence file A.m should declare the function as:

function [Out] = A(AA, Cal)

While file B.m should do it as:

function [Out] = B(AA, Cal)

but preferably use better names than A and B.

Upvotes: 2

Jeremy Dorner
Jeremy Dorner

Reputation: 208

The only way for you to call a function from another m file is if that function is defined as its own m-file (fun.m) or if you copy and paste the fun definition to B.m

Addressing your previous comment, it sounds like you had a script file that calls a function, and that function is defined within the script. To follow the advice given by that answer, you would have to make a separate m-file that only contains the function definition

Upvotes: 1

Related Questions