フィルターのクリア

How to use relative path to use matlab file in another computer

713 ビュー (過去 30 日間)
Harsha
Harsha 2015 年 10 月 26 日
コメント済み: Lucas Ritzdorf 2024 年 3 月 3 日
I have a folder in P:\study\Main. Inside the "Main" folder there is another sub folder called "Sub". There is a m file in main called "main_s.m". This refers another m file called "S2S.m" in "Sub" folder. To do this I had to use addpath('P:\Study\Main\Sub') in the m file. when I copy "Main" in to another computer different drive and execute "main_s.m" it will lead to an error. Is there a way to write a path which can be used in anywhere without altering the code in the m file?
  2 件のコメント
Stephen23
Stephen23 2015 年 10 月 26 日
You should read about absolute and relative filepaths:
Unless you really have total control over every computer where your code is run then you should take into consideration that hard-coding an absolute path is a poor idea, as it requires changing the code in order to change the location. It is better to make the path relative to the current directory, or force the user to select a root directory (e.g. by using a user interface, as an input argument, or by some setup file).
Samuel
Samuel 2015 年 10 月 27 日
In this case
addpath('Sub')
in your main_s.m should do the trick as long as sub stays in the main folder.

サインインしてコメントする。

採用された回答

Dennie
Dennie 2015 年 10 月 26 日
編集済み: Dennie 2015 年 10 月 26 日
You can use .\<folder_name>. The '.\' denotes that the current folder should contain the specified folder. So, having the code in the Main folder, the path should look like this:
addpath('.\Main\Sub')
  3 件のコメント
Stephen23
Stephen23 2015 年 10 月 27 日
It is normal if that directory does not exist. If there is no directory in that location with that name then you will get that warning.
Lucas Ritzdorf
Lucas Ritzdorf 2024 年 3 月 3 日
Worth noting that, if you're trying to build something like a Git repo (or other project folder that's intended to be portable), you can use this addpath() invocation from a startup.m file in that folder.

サインインしてコメントする。

その他の回答 (1 件)

Adam
Adam 2015 年 10 月 26 日
編集済み: Adam 2015 年 10 月 26 日
The safest way is probably to use
currentFile = mfilename( 'fullpath' );
which will give you the path of the currently executing m-file (i.e. your main_s.m), then you can just do e.g.
[pathstr,~,~] = fileparts( currentFile );
addpath( fullfile( pathstr, 'Sub' ) );
This will ensure that the path is always relative to that of the m file in which you put the code.

カテゴリ

Help Center および File ExchangeSearch Path についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by