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

2 Answers

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

1

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 preferable use better names than A and B.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like