Why can't MATLAB find a script that is on MATLABPATH - matlab

I've just created a script file in MATLAB, but can not run it. The name of my script is getEnvFiles.m. When I first tried to run it, I got the following result:
>> getEnvFiles
'getEnvFiles' is not found in the current folder or on the MATLAB path, but exists in:
\\wsl$\ubuntu\home\me
Change the MATLAB current folder or add its folder to the MATLAB path.
So, I added this directory (which is actually the current directory) to the search path, but still got the same result:
>> addpath('\\wsl$\ubuntu\home\me')
>> getEnvFiles
'getEnvFiles' is not found in the current folder or on the MATLAB path, but exists in:
\\wsl$\ubuntu\home\me
Change the MATLAB current folder or add its folder to the MATLAB path.
When I check the path, it looks like this directory is on the path:
>> path
MATLABPATH
\\wsl$\ubuntu\home\me
I can further verify that this directory is my present directory:
>> pwd
ans =
'\\wsl$\ubuntu\home\me'
and that getEnvFiles.m is in this directory:
>> ls
. .emacs.d HarborData
.. .emacs~ RawHarborData
.bash_history .landscape at
.bash_logout .motd_shown getEnvFiles.m
.bashrc .profile test.m
.bashrc~ .sudo_as_admin_successful
.emacs
Is the issue that I'm using wsl (Windows Subsystem for Linux), or do I have some other misunderstanding?

Type rehash and then try running your script again. Even though you have added the new directory to your path, you need to update the path cache so that it knows about the new scripts it can see.

The problem seems to lie in WSL's ability to add new files to the directory. When I create a new script within MATLAB, and try to run it, I get the problem discussed above. However, running already existing files is not a problem. For now, my only solution is to close MATLAB after creating a new script and reopen it. Then, I can run it. Although, oddly, I can't open it in MATLAB's editor.....

This may or may not help, but ...
Sometimes you have to prepend execution with .\ in order to run scripts in PowerShell or from within the command prompt (in Windows, I'm not sure about other operating systems).
I get this error quite often, especially when not in Admin mode.

Does this work?
% Get path of executing script.
filePath = matlab.desktop.editor.getActiveFilename; % Note that this isn't necessarily the same as the output of 'pwd()'.
% Or: filePath = mfilename('fullpath')
% Make sure all nested directories of filePath are on the path, then tell MATLAB where you're working.
addpath( genpath( filePath ) ); % If this fails, try one folder up the tree:
% addpath( genpath( fullfile( filePath, '.' ) );
cd( filePath );
Alternatively, it looks like you might have written and saved the script, and then typed it into the command window to execute. If it's not a special type of script (Function/Class/GUI/etc.) then you can simply click 'Run' in the Editor tab (or the F5 key) and MATLAB should prompt you with a 'Change Folder' option, to which you should acquiesce.
If you're running this script through the WSL terminal, try my suggested code.

Related

Load file in matlab ralative to script location

I have a simple script in matlab and I want to load a file. It seems it only works if the file is in the same dir as the script. If I add the file to a directory it does not read it.
For example:
fileID = fopen('myfile','r' ,'n', 'US-ASCII');
but when I put myfile in files:
fileID = fopen('files/myfile','r' ,'n', 'US-ASCII');
or
fileID = fopen('./files/myfile','r' ,'n', 'US-ASCII');
I get a -1 as a fileID. File cannot be read.
As per the comments, this is happening because you most likely added the path of where the script was located to your MATLAB path but you did not add the subdirectory where the file was in to your path. This is why it can't find the file. Therefore to avoid this in the future, you need to physically change the directory (i.e. the Working Directory) of where MATLAB is currently operating to where your script is stored.
It is then where local referencing should work. You can do this by either using the cd function, going to the top of your MATLAB window where you see the directory listing, clicking on the arrow to the right and pulling a drop down menu to change the directory, typing the actual directory you want by clicking on any blank space in the directory listing to enable a text box:
... or if you are running the code in the MATLAB editor, it'll request that you change directories as the script you are trying to run is not currently located in the working directory.
You can also programmatically add the subfolders in your script directory using mfilename, fileparts, genpath and addpath:
[dir, ~, ~] = fileparts(mfilename('fullpath')); % locate your script directory
addpath(genpath(fullfile(dir))); % add the folder and all subfolders to Matlab search directory
% then load your file.
fileID = fopen('myfile','r' ,'n', 'US-ASCII')
If it is also important that all outputs should be placed within the same directory as your script file, you can cd to your script directory:
cd(dir)

MATLAB startup.m ignores cd?

in my startup.m-file I call a script init.m. In this init file I determine the folder containing this file, want to set the current directory to this folder and continue with some other initialization stuff.
But when I start Matlab, the file will be executed, but the cd command seems to be ignored and the directory won't get changed. Does somebody know why? I.e. the matlabpath variable is extended by the subfolders....
startup.m:
run 'D:\FloatingZone\mscrystalgrowth\trunk\MATLAB\FzKameradaten\FzCameraEvaluation\init.m';
init.m
% get path to folder containing this function
folder=mfilename('fullpath');
file=mfilename();
folder=folder(1:end-length(file));
% change folder
cd(folder);
% add subfolder to the top of the MATLAB path
addpath(genpath('Tools'));
MATLAB did exactly what you told it; there's nothing special about the startup scripts.
From the documentation for the run command:
run changes to the folder that contains the script, executes it, and resets back to the original folder. If the script itself changes folders, then run does not revert to the original folder, unless scriptname changes to the folder in which this script resides.
So your cd command didn't actually do anything, run had already changed the directory. And then changed it back, exactly as expected.
I'm not 100% clear on what you want your startup to do. As already pointed out run is working correctly.
Alternative startup.m
if isdeployed == false
cd 'D:\FloatingZone\mscrystalgrowth\trunk\MATLAB\FzKameradaten\FzCameraEvaluation\'
init();
end
function init.m stored in your FzCameraEvaluation\ folder.
function init
addpath ( genpath ( '../Tools' ) );
end
Does that work?

Changing working directory in matlab to current script dir with running blocks

Is there a way to change the current working directory to current script directory with running code just inside one block of script? Script folder is not added to path.
Redefined: Is there a way to to change the current working directory to script that's currently active in editor?
I found the solution (was looking in wrong direction before).
tmp = matlab.desktop.editor.getActive;
cd(fileparts(tmp.Filename));
You can use mfilename to get the current script name, cd(fileparts(mfilename)) should change to the correct directory.
If you frequently have to run scripts which need to be run in their script directory, you can use this function:
function varargout=run_in_dir(fun,varargin)
location=which(func2str(fun));
assert(exist(location,'file')~=0,'fun does not seem to be a m. file');
old_dir=pwd;
cd(fileparts(location));
try
if ~isempty(varargin)
[varargout{1:nargout}]=fun(varargin{:});
else
[varargout{1:nargout}]=fun();
end
catch ME
cd(old_dir)
rethrow(ME)
end
cd(old_dir)
end
To run sin(3) in the directory where sin is defined, use run_in_dir(#sin,3)

Matlab function call directory

So i had this issue that occurred when I ran a Matlab script. Here is an a simple example that illustrates it:
So its important to outline the file structure:
MainFolder
script.m
SubFolder
a1.csv
a2.csv
a3.csv
now say i have a script like this:
-> script.m
dir
it would simply print out the files in the folder.
Now the wierd thing, if i run the script in the Subfolder like this:
>>script
it will do this:
>> a1.csv a2.csv a3.csv
but if i do this in the folder:
>>run('C:\Users\....\MainFolder\script.m')
it will only print out
>> script.m
So obviously it is acting as if i ran it form MainFolder rather than SubFolder.
What is the point of this functionality?
The dir command shows the directory contents of Matlab's current directory, not that of where the script is located. So the script showed you the directory contents of wherever you happened to be in the Matlab command prompt when you called that script.
To get what you want, use this in the script:
dir(fileparts(mfilename('fullpath')))
Use pwd to see current dir
Use cd to change directory
Use path to see if your project folders are included in the path
Use which to see you are calling the right *.m file (in case there is multiple .m files with same name on the path)

Problem with the system command in MATLAB

I am using the system command in MATLAB as follows (with the current directory being 'scripts'):
[status, result] = system('cd ..\\TxtInOut')
However, invoking the system command does not seem to work. It returns status = 0 and result = ''.
Any suggestions?
If you want to change directories, you should use the CD command. The argument can be either a full path or relative path:
cd('c:\matlab\toolbox'); %# Full path to a directory
cd('scripts'); %# Move to a subdirectory "scripts"
cd('..\TxtInOut'); %# Move up one level, then to directory "TxtInOut"
If you want information about a directory, you should use the DIR command. DIR will return an m-by-1 structure of information for a directory, where m is the number of files and folders in the directory. Again, the argument can be either a full path or relative path:
data = dir('c:\matlab\toolbox'); %# Data for a full path to a directory
data = dir('scripts'); %# Data for a subdirectory "scripts"
NOTE: When working on different platforms (i.e. Windows or UNIX), you will have to pay attention to whether you use the file separator \ or /. You can get the file separator for your platform using the function FILESEP. You can also build your file paths using the function FULLFILE.
Any command executed by "system" is external to MATLAB. A command shell is generated, executes your request, and then returns the result. The 0 result indicates successful completion: the command shell changed its current directory as requested and then returned. (Command shells use non-zero to indicate an error, because there are usually many more ways that a program can fail than succeed.) Unfortunately that only affects the command shell's current directory - see gnovice's answer for how to actually change the directory.
you can use cd, dir, ls, etc directly in matlab without call system functions.
You can also use the underlying operating system commands by preceding them by an exclamation sign.
For instance:
!dir will show you the current directory contents in Windows
!pwd will show you the current directory in Linux/Mac
But calling cd does not change the current directory!