1

From what I understood of matlab, if you want to define a function and use it in your "main file" you need to write the function in a separate file and to call it at the beginning of your "main file" with addpath('...\myfunction.m').

Now let's say I define a function f1 in a file f1.m that I use in main.m, if I want to define a function f2 (in another file) that needs to call f1, can I use addpath()...\f1.m in my f2.m file ? Or what is the best way of calling f1 in f2 ?

3 Answers 3

2

The best way to do that is having your functions at same folder, or you'll need to add folder by folder. So if you put f1.m, f2.m, f3.m at different folders, you have to call a addpath for every function. If you have a folder 'myfunctions', all you need to do is addpath('...\myfunctions\').

If you have a folder named myfunctions with your functions at same folder of you main script, you just have to add that folder to path. For example:

%Main script
addpath('myfunctions')
x = -0.5 + rand(100,1); 
y = -0.5 + rand(100,1);
[a,b] = f1(x,y);

Inside the folder myfunctions you have the files f1.m and f2.m:

function [a,b] = f1(x,y)
a = x + y;
b = f2(a);
end
function b = f2(inp)
b = inp<0;
end

You can't use addpath with a file, it has to be a folder.

Sign up to request clarification or add additional context in comments.

1 Comment

When I do so I get a syntax error telling that: function name f1 is known to MATLAB by its file name: 'myfunctions'
0

Save all your files in the folder where matlab is opened, and you wont need addpath to explicitly tell matlab to search in the told directories for files

Comments

-1

You should create a startup.m file that you run at the start. located in your current directory. This should include all of your paths you need to add.

So your m file would look like :

startup
f1
f2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.