Finding the path of installed program from MATLAB? - matlab

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.

Related

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

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.

How can I recapture the specificity of old IPython filesystem path autocompletion?

On Windows, IPython is the easiest-to-use command-line environment I have available. In my really old IPython environment (Python 2.7.5, IPython 0.13.2, and pyreadline 2.0), I used to be able to type a partial file path at the command line, press tab, and get something like this:
In [1]: cd /Users/Jez/D
/Users/Jez/Desktop/ /Users/Jez/Downloads/ /Users/Jez/dots2-default-accel=6da3a.pdf
/Users/Jez/Documents/ /Users/Jez/Dropbox/
All of the options it presents are bona-fide files and directories. That's good.
With a newer setup (Python 3.6.4, IPython 6.1.0, (py)readline???) the following happens:
In [1]: cd /Users/Jez/D
delattr() dir() /Users/Jez/Desktop/ /Users/Jez/Dropbox/
DeprecationWarning display() /Users/Jez/Documents/
dict divmod() /Users/Jez/Downloads/
Despite the fact that what has been typed so far is only meaningfully interpretable as a filesystem path, the completion options include a whole lot of things that aren't files or directories (as if I might want to divide a non-existent object called /Users/Jez by something). This is less smart. I find it quite frequently derails my train of thought (in this example there are only 6 false positives, but sometimes there are so many that the bona-fide options are completely hidden).
Is there a configuration option somewhere that can allow me to re-capture the specificity of the old behaviour? My search-foo has failed me so far - I've found a few references to readline and .inputrc but I suspect that's irrelevant for Windows.
Got it:
%config IPCompleter.use_jedi = False
or equivalently in /Users/Jez/.ipython/profile_default/ipython_config.py:
c = get_config()
...
c.IPCompleter.use_jedi = False
Order 66 complete. What a relief.

MATLAB parse OS-specific path

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

Perl Statistics::R generates blank plot image (jpeg)

I am currently using ActiveState Perl 5.14 and the R project version 2.13.2. Within Perl I am using Statistics::R version 0.08. According to ActiveState the more recent versions of Statistics::R (through 0.24) failed to pass scrutiny and are therefore not available through the PPM.
History: I have been successfully using Perl to access R for some time to perform analysis. Now I want to generate JPEG images of the results of the analysis for easy visualization.
Here's the problem: I can generate the images successfully from within the R console. However, when I run the same commands through Perl I only get a blank image. My console code includes (simplified, of course):
x<-c(1,2,3,4,5)
y<-c(5,4,3,2,1)
jpeg("C:/temp.jpg")
plot(x,y)
dev.off()
And my Perl commands include (also simplified):
$R = Statistics::R->new();
$R->start_sharedR
$R->send("x<-c(1,2,3,4,5)");
$R->send("y<-c(5,4,3,2,1)");
$R->send('jpeg("C:/temp.jpg")');
$R->send("plot(x,y)");
$R->send("dev.off()");
Any suggestions? I know that there are other plotting options accessible to Perl. I have eliminated some (GD Graph) because X-axis data is not treated as numeric. I'd prefer to keep it in R if at all possible since I'm already interacting in that package for the analysis. Thanks!
Forget Statistics::R. Just use a system call. At least it's what I do!
my $path_to_r = "C:/Program Files/R/bin/Rscript.exe";
my $cmd = "x<-c(1,2,3,4,5);";
$cmd .= "y<-c(5,4,3,2,1);";
$cmd .= 'jpeg("C:/temp.jpg");';
$cmd .= "plot(x,y);";
$cmd .= "dev.off()";
system($path_to_r . " -e '" . $cmd . "'");
If your R script grows up a bit or if it takes input from the parameters, write it in a file and Rscript.exe this file.
It works fine for me with Statistics R::0.27, but not with 0.08, the only version I could find in Active perl's package manager. In order to install 0.27, I had to use cpan command line. Make test fails but make install was fine. Bit of a life-saver.
(By the way I'm a relative noob. Using cpan command line was pretty easy however.
Type i /Statistics-R/ from cpan command line, then
install FANGLY/Statistics-R-0.27.tar.gz (or whatever the relevant file is. I'm using a windows system so RSPerl annoyingly not an option for me. I note that latest Statistics::R version is dated March 2012 so perhaps some of the previously documented (piping?) problems have been solved. You may also need to install a 'maker'; in my case it was 'dmake', not 'nmake'. Pretty easy, you can get a version of make from M$ website and copy that + .err file into PERL\bin dir. But help on this is available elsewhere. Hope this helps!)

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!