How do I access a .m file in a subfolder?

101 ビュー (過去 30 日間)
Benjamin Pommer
Benjamin Pommer 2022 年 9 月 5 日
回答済み: Image Analyst 2022 年 9 月 5 日
Hi Matlab community,
how do I access a .m file in a subfolder? In my case, the name of the subfolder would be "Workspace" and the name of the file in the subfolder would be "constants.m".
Best regards
  4 件のコメント
Stephen23
Stephen23 2022 年 9 月 5 日
"I want to open a .m file with a command in another .m file."
This is still unclear: do you want to FOPEN the file? (i.e. open the file for reading/writing using FSCANF/FPRINTF/...)
Or do you mean open in the sense of using some app installed on your computer to open the file? Or something else?
When you are not precise with explaining what you want, then you delay getting an answer.
Benjamin Pommer
Benjamin Pommer 2022 年 9 月 5 日
Actually, I wanted to open and run the file to get the variables in my workspace to further process them in my current file.

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

採用された回答

Rik
Rik 2022 年 9 月 5 日
編集済み: Rik 2022 年 9 月 5 日
If you want the read the file as text:
You can use a relative path:
txt=fileread(fullfile('Workspace','constants.m'));
You can also include the current working directory explicitly:
txt=fileread(fullfile(pwd,'Workspace','constants.m'));
Edit:
If you want to run the m file, that depends on whether it is a function or a script. You need the run function for a script file. For a function you should add the folder to your path and simply call the function.
  1 件のコメント
Benjamin Pommer
Benjamin Pommer 2022 年 9 月 5 日
thank you

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 9 月 5 日
Add it to your path. In your main script, have this line
addpath(genpath(pwd));
After that you should be able to call any other scripts or functions in your "Workspace" subfolder or any other subfolders of where your main script lives.
If you want to make that permanent, then also call savepath
savepath;

カテゴリ

Help Center および File ExchangeLow-Level File I/O についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by