Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a file or calling a function whose file is placed in another folder with MATLAB?

Tags:

matlab

Tried Googling, but couldn't find anything.
I have a few files and folders in my current MATLAB folder.
One of those folders is called 'Map' and it has a 'map1.m' file which I want to call from my code in the current MATLAB folder.
In my code, I can't call it like this:

/Map/map1; 

but I can do so like this:

cd Map; map1; cd ..; 

Somehow the above method seems incorrect. Is there a more elegant way to do it?

like image 573
Nav Avatar asked May 27 '11 14:05

Nav


People also ask

How do you access files in a folder in MATLAB?

On the Home tab, in the File section, click Open , and then select a file to open. You also can double-click the file in the Current Folder browser.


1 Answers

You can run the file without adding the folder to your path manually, using the run command, which is specifically for such cases. From the documentation:

run is a convenience function that runs scripts that are not currently on the path.

You call your function/script as

run /Map/map1  

If you want to run the function/script by merely entering its name and not with the full (or relative) path, then you should add the folder to your path.

As noted by @mutzmatron, you cannot use run to call functions with input/output arguments. So, unless if it's a script/function without input/output arguments, using run will not work and you'll have to add the folder to your path.


EDIT

Just as a matter of good coding practice, and to work in cases where your function has inputs/outputs, adding/removing the folder from your path is the correct way to go. So for your case,

addpath /Map ...  map1;  ... rmpath /Map 

The important thing is that your function call is sandwiched between the addpath and rmpath commands. If you have functions of the same name in both folders, then you should sandwich it tighter i.e., a line before and a line after, so as to avoid conflicts.

like image 60
abcd Avatar answered Oct 03 '22 21:10

abcd