I am running a MATLAB project, which is shared by several users, some running Windows and some running Linux.
In some of the scripts, I need to access files which are in external directories, and which I do not want to add to the MATLAB path.
To accommodate both Linux and Windows, I need to be able to determine the type of OS I'm running, and to set the directory separator accordingly ('\' for Windows, '/' for Linux).
I tried
os = getenv('OS')
(which I saw in some official guide),but it returns an empty string.
I could check the first character of 'pwd', but that's pretty ugly, and I expect that there should be something simpler.
Thanks for any suggestions!
To use correct directory separator you don't need to write code to handle different operating systems. filesep gives you the correct directory separator.
My1stDir = 'Year2012';
My2ndDir = 'Feb';
My3rdDir = 'Day03';
MyDir = [ 'mydata', filesep, My1stDir, filesep, My2ndDir, filesep, My3rdDir ];
In Linux you'll get:
MyDir =
mydata/Year2012/Feb/Day03
In Windows you'll get:
MyDir =
mydata\Year2012\Feb\Day03
Related
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.
I'm currently trying to write a program that requires I access files on a OneDrive folder that will be shared with multiple computers. Currently, an issue is appearing where the 'system' command is throwing an error when I try and access the OneDrive folder because the full path name has spaces in it.
folder = '/Users/myuser/Desktop/OneDrive\ -\ -\ Company\ Name/foldername-AVL'
STR = sprintf('cd %s',folder);
system(STR)
The error I keep receiving is
/bin/bash: line 0: cd: %s/Users/myuser/Desktop/OneDrive: No such file
or directory
So it is effectively cutting off all entries after the second space. I've looked through the documentation and all, and I can't seem to find a solution or a guide for using the system command in this specific situation.
I am guessing that you are trying to escape the spaces. In general I prefer to wrap all arguments that have spaces with double quotes. I would have guessed that escaping the path would work as well, but maybe not ...
This should work ... and it is much easier to read (IMHO).
folder = '"/Users/myuser/Desktop/OneDrive - - Company Name/foldername-AVL"'
STR = sprintf('cd %s',folder);
system(STR)
OR - moving " to sprintf
folder = '/Users/myuser/Desktop/OneDrive - - Company Name/foldername-AVL'
STR = sprintf('cd "%s"',folder);
system(STR)
I'm using Sphinx on a Linux production server as well as a Windows dev machine running WampServer.
The index configurations in sphinx.conf each require a path setting for the output file name. Because the filesystems on the production server and dev machine are different, I have to have two lines and then comment one out depending on which server I'm using.
#path = /path/to/folder/name #LIVE
path = C:\wamp\www\site\path\to\folder\name #LOCALHOST
Since I have lots of indexes, it gets really old having to constantly comment and uncomment dozens of lines every time I need to update the file.
Using relative paths would be the ideal solution, but when I tried that I received the following error when running the indexer:
FATAL: failed to open ../folder/name.tmp.spl: Invalid argument, will not index. Try --rotate option.
Is it possible to use relative paths in sphinx.conf?
You can use relative paths, but its kind of tricky because you the various utilities will have different working directories.
eg On windows the searchd service, will start IIRC with a working directory of $WINDIR$\System32
on linux, via crontab, I think it has working directory left over from previously, so would have to change the folder in the actual command line
... ie its not relative to the config file, its relative to the current working directory.
Personally I use a version control system (SVN actually) to manage it. The version from Dev, is always the one commited to the repository, the 'working copy' on the LIVE server, has had the paths edited to the right location. So when 'update' to the latest file, only changes are merged leaving the local filepaths in tact.
Other people use a dynamic config file. The config file can be a script (php/python/perl etc) - but this only works on linux so wont help you.
Or can just have a 'publish' script. Basically, you edit a 'master' config file, and one that can be freely copied to all servers. Then a 'publish' script, that writes the apprirate local path. It could do it with some pretty simple search replace.
<?php
if (trim(`hostname`) == 'live') {
$path = '/path/to/folder/';
} else {
$path = 'C:\wamp\www\site\path\to\folder\`;
}
$contents = file_get_contents('sphinx.conf.master');
$contents = str_replace('$path',$path,$contents);
file_put_contents('sphinx.conf',$contents);
Then have path = $path\name in the master config file, which will get replaced to the proper path, when run the script on the local machine
Can I find out from the MATLAB command line what is the installation path of specific program?
Or can I find the path for a registered program (Windows reg equivalent)?
This won't be 100% reliable, but this will get the right answer most of the time:
function p = findOnSystemPath(f)
p = '';
path = getenv('path');
dirs = regexp(path,pathsep,'split');
for iDirs = 1:numel(dirs)
tp = fullfile(dirs{iDirs},f);
if exist(p,'file')
p = tp;
break
end
end
Sample usage:
>> findOnSystemPath('runemacs.exe')
ans =
C:\Program Files (x86)\emacs\bin\runemacs.exe
Depending on your OS, you might be able to get this information from the system directly:
which is available on Unix systems and Windows systems with Cygwin installed:
>> [~,p] = system(sprintf('which "%s"',f))
p =
C:/Program Files (x86)/emacs-mw-a/bin/runemacs.exe
where is available on Windows 2003 and later:
>> [~,p] = system(sprintf('where "%s"',f))
p =
C:\Program Files (x86)\emacs-mw-a\bin\runemacs.exe
And in some cases, you can pull this information from the registry using winqueryreg, for example:
>> notepadEdit = winqueryreg('HKEY_CLASSES_ROOT','Applications\notepad.exe\shell\edit\command')
notepadEdit =
C:\Windows\system32\NOTEPAD.EXE %1
Call the DOS/bash command which, e.g.,
!which matlab
!which notepad
(Or use system instead of the !.)
EDIT: It seems that there isn't a direct equivalent in Windows. I had cygwin installed on the (Win XP) machine I tried it on, and the command succeeded. Alternatively, take a look at these answers on stackoverflow and superuser.
This depends on what you know about the OS and what properties your program has.
On Linux I usually do something like:
[error, path] = system(sprintf('which "%s"',programName));
It doesn't look pretty and it's far from portable (I suppose it will not work on Windows, perhaps only if you install Cygwin or something similar). It's far easier in Unix since most executables are accessible from the "path" (the environment variable "path"), while in Windows most executables are either stored in the Windows directory (which is in the default path, so they are found) or in a Program Files directory which is not as far as I recall.
Error = 0 when the program is found and path then obviously contains the path to the executable.
For Windows I guess you can search all directories for the program, but that might be somewhat tedious.
MATLAB is not really designed to be used as a tool to search files anywhere on the drive. That's a task best left to the OS, and what Egon suggested is what you should be doing. Simply replace which with the equivalent in DOS (you should know this already, else just ask another question in the MS-DOS/Windows tag. It probably has already been answered.).
If you are really hell bent on using MATLAB to search the drive, then you can do the following
addpath(genpath('C:\')); %#' I am not sure which way the slash is
which filename
Beware, the first step will take a while.
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!