How can I get script's location when running one section of a script?
11 次查看(过去 30 天)
显示 更早的评论
I frequently run scripts one section at a time. I can be using different computers, remote desktops, etc., so the path changes. The load and save commands are relative to the present working directory rather than the directory of the script, which causes problems if the present working directory isn't where the script is. When running a whole script, I can use either mfilename('fullpath') or dbstack('-completenames') to get the directory the script is in, but this doesn't work when running a section. How can I achieve this? None of the following work:
% Returns 'C:\Users\MyName\AppData\Local\Temp\Editor_mddon\LiveEditorEvaluationHelperE847216552.m'
stk = dbstack('-completenames');
filepath = stk(1).file
% Returns 'C:\Users\MyName\AppData\Local\Temp\Editor_mddon\LiveEditorEvaluationHelperE847216552.m'
mfilename('fullpath')
% Returns wrong filename, because I've moved to another script by the time
% it gets to this line.
filePath = matlab.desktop.editor.getActiveFilename
If it's impossible with MATLAB code, perhaps there is a Java-based workaround?
0 个评论
回答(2 个)
Steven Lord
2024-6-13
Rather than depending on what is the current directory when running the code (which is subject to change when you're running the code by sections, as you've already noticed) why not store the data in a fixed location that you can compute using functions included in MATLAB? On the same computer I believe tempdir will be the same across MATLAB sessions unless you explicitly change one of a few environment variables. If you need a temporary file name, you can use tempname or use fullfile to append a name of your choosing to tempdir.
If you have multiple machines tempdir can return different directory names (a directory name that works on Linux won't work on Windows and vice versa, for example) but it will be a valid temporary directory name for the machine on which you're working.
td = tempdir
tn1 = tempname
tn2 = tempname('c:\Temp') % Yes, writing here almost certainly won't make sense on Linux
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!