I want to create a function that finds a specific path in Matlab.
The issue is that the path is variable depending on the versions of my program I am working, so
..../...../v1.1/file.m
or
.../...../v1.2/file.m
I would like to know if there is a function to use for hte variable name. Also if the path is too long and I do not want to write it all, is there a symbol that replaces all the previos part. I mean:
strfind(path,$/v1.1/file.m);
But I am not sure of it.
I would appreciate some help!
If you are looking in the path for an instance of the version number, v1.X, then you should just feed it too regexp.
With regard to storing the root of the path and combining it with the version specific portion, I usually use fullfile which handles the path separator for you and makes your code system independent. Finally, in order to handle the version numbering I use sprintf. A lot of people in my lab prefer to use array concatenation, but I find code like that harder to read.
root = matlabroot; % Just an example of a root
version = 1; % Make this a variable in case of future upgrades
subversion = 1; % The actual part from the question
fullPth = fullfile( root, sprintf('v%i.%i', version, subversion), 'file1' );
Do you want to do something similar to this?
versionOfProgram = 'v1.2';
f = fullfile('C:', 'Applications', 'matlab', versionOfProgram, 'file.m');
Related
MATLAB has some great tools, among which this dependency listing function stands out. I'm wondering, is there a way to perform the inverse operation?
That is, fList = matlab.codetools.requiredFilesAndProducts(files) takes a function or script and returns a list of all of the dependencies. I am trying to do the opposite: given a function, I want to find all the functions where this function is called, perhaps limited to the scope of my working directory.
The only solution I can think of is a brute force approach (which would be painfully slow given the speed of matlab.codetools.requiredFilesAndProducts). In MATLAB-esque pseudocode:
foi = file of interest
files = empty set of file lists
i = 0;
for all files f in dir
files{i} = matlab.codetools.requiredFilesAndProducts(f);
i = i + 1;
end
find indices in files where list contains foi
Surely there must be better way.
The best solution I have found is to use the MATLAB "find files" tool (in the latest versions, it is a button on the editor window). It is actually extremely fast, and you can have it search all the .m files in a directory structure, and return every line where a particular string is used - like say, the name of your function.
See if the Parents listing in the dependency report is what you're looking for. It only looks in the current directory, and it has some exclusions.
I am reading 50 files from a folder as follows:
list_of_files=dir(fullfile('/home/user/Desktop/MTP/schemes/o33smnpimp/data/', '*.dat'));
My problem is until & unless I have same exact folder opened as path in MATLAB path (one above the path window) this command won't work. What is the reason behind this? Actually there are multiple schemes and every time I need to run a particular scheme, I have to go to the data folder of that particular scheme. How can it be solved?
The issue is that you can get the list of files using the full path like you have but you ALSO need to specify the full path when you use it. For example, try changing your code to:
baseDir = '/home/user/Desktop/MTP/schemes/o33smnpimp/data/'; % <--- will use this twice
list_of_files=dir(fullfile(baseDir, '*.dat'));
for ind = 1:length(list_of_files)
myFilenameFull = fullfile(baseDir, list_of_files(ind).name); % <---- must use fullfile here too!
D1 = getData(myFilenameFull, 'stuff');
end
sometimes I load a .m file to work in the workspace, but I usually forget what is the recent file I´ve opened. So in the same way that you write who and you can see the variables of the workspace I suppose there should be a command to know what is the .m file in which you are working.
Does anyone know a command like this?
Thank you so much.
For newer MATLAB versions, there is a way to get the fullpath of the file currently being edited in the Editor:
if verLessThan('matlab', '7.10')
%# not supported
fname = '';
elseif verLessThan('matlab', '7.12')
%# R2010a,R2010b: editorservices
fname = editorservices.getActiveFilename;
else
%# R2011a: matlab.desktop.editor API
fname = matlab.desktop.editor.getActiveFilename;
end
mfilename seemed to be the right choice, but it returns an empty string when called from the command line. Therefore you may check the 'command history' provided by the IDE.
For larger projects it most often makes sense to use MATLAB's object model or at least functions in order to structure your work. Working in the 'workspace' often results in unwanted side effects.
I do something like this to bootstrap runs:
%%
params.run = 'hairy.m';
params.hair = 10;
setup_defaults(params);
run_lots_of_code(params);
This has advantages as it hides the 'globals' in a single global (params), and the global tells you where they came from.
I'm a total newbie to MATLAB but I have to write some code in it. I've had problems with making MATLAB see functions I've defined in external .m files. This is what I've done: I've created a file named, say, foo.m in my home dir with the following contents:
function [y] = foo(x)
% description
y = x + 1
When I run matlab (my home dir is matlab's workdir) it does not see foo function - it replies with standard ??? Undefined function or variable 'foo' message. BUT help foo or which foo return correct data printing help text and pointing on foo.m file respectively.
I must be missing something but I have no idea what it is. This is getting very annoying.
Oh, after several trial and error attempts I've managed to call that function. Unfortunately I can't remember the sequence of steps I've performed. Moreover after restarting matlab it returns to its usual 'Undefined function or variable' response.
I have 7.11.0.584 matlab running on linux.
MATLAB needs to be told which directories to search over to access those m-files. Clearly it cannot be left to search over your entire disk drives. The MATLAB search path is a list of directories that will be searched in specific order to find your functions.
help addpath
help pathtool
You should never put those files anywhere in the official MATLAB toolbox directories. Choose an entirely separate directory.
Finally, be careful not to name your own functions to match the names of existing MATLAB functions. Otherwise, your very next question here will be why your code does not work properly. This is a common cause of strange and confusing bugs.
It seems you're having some trouble with addpath. Try opening the file in the matlab editor and adding a break point in the file. If the file is not on Matlab's path, matlab should ask if you want to change directory or add the file to the path, choose add to the path.
If this doesn't work, try changing the current working directory (displayed in the main window) to the same location as the m file and calling the function. If this doesn't work you're either getting the name wrong ar there's possibly something wrong with your installation.
Occasionally matlab has problems if it does not have write permission to the directory the file's in, so check that too, i.e. make sure admin rights aren't required for the directory or m file.
Oh, and try:
clear functions
to reload all functions into memory.
The function needs to be in MATLAB's path. Use pathtool to tell MATLAB where to find your function. Note that if you name a function the same name as an existing function, MATLAB will use whichever function it finds first according to the order that the paths are listed as you see them in pathtool.
Although coming late but I hope it will help someone.
If in the folder where the function you are calling is residing, there is any other function with the same name as one of the functions from MATLAB toolboxes, then Matlab will not recognize its license and therefore will disable the whole folder from execution, no matter it is properly added to the path. The help will display though.
In order to check it, type:
which name_of_func.m
and you will get the path with "%Has no license available" message.
If it is your own function, you should not get this message but only the path.
Therefore, find the function in this folder which has the same name as a MATLAB toolbox functions, and rename it. I will solve the problem :).
Best Regards
Wajahat
I run MATLAB on both Linux and Windows XP. My files are synced among all of the computers I use, but because of the differences in directory structure between Linux and Windows I have to have separate import and export lines for the different operating systems. At the moment I just comment out the line for the wrong OS, but I am wondering if it is possible to write something like:
if OS == Windows
datafile = csvread('C:\Documents and Settings\Me\MyPath\inputfile.csv');
else
datafile = csvread('/home/Me/MyPath/inputfile.csv');
end
This is also a more general question that applies in cases where one wants to execute system commands from within MATLAB using system('command').
You can use ispc/isunix/ismac functions to determine the platform or even use the computer function for more information about the machine
if ispc
datafile = csvread('C:\Documents and Settings\Me\MyPath\inputfile.csv');
else
datafile = csvread('/home/Me/MyPath/inputfile.csv');
end
To follow up on Amro's answer, I was going to just make a comment but struggled with the formatting for the code.
I'd prefer to split the OS selection from the file read.
if ispc
strFile = 'C:\Documents and Settings\Me\MyPath\inputfile.csv';
else
strFile = '/home/Me/MyPath/inputfile.csv';
end
try
datafile = csvread(strFile);
catch
% setup any error handling
error(['Error reading file : ',strFile]);
end
That way if I need to change the way the file is read, perhaps with another function, it's only one line to change. Also it keeps the error handling simple and local, one error statement can handle either format.
Just to add a minor point to the existing good answers, I tend to use fileparts and fullfile when building paths that need to work on both UNIX and Windows variants, as those know how to deal with slashes correctly.
In addition to using the various techniques here for dealing with path and file separator differences, you should consider simply trying to avoid coding in absolute paths into your scripts. If you must use them, try to put them in as few files as possible. This will make your porting effort simplest.
Some ideas:
Set a fileRoot variable at some early entry point or config file. Use fullfile or any of the other techniques for constructing a full path.
Always use relative paths, relative to where the user is operating. This can make it easy for the user to put the input/output wherever is desired.
Parameterize the input and output paths at your function entries (e.g., via a system specific context object).
If the directory structures are within your home directory you could try building a single path that can be used on both platforms as follows (my Matlab is a bit rough so some of the syntax may not be 100%):
See here for how to get the home directory for the user
Create the path as follows (filesep is a function that returns the file separator for the platform you are running on)
filepath = [userdir filesep 'MyPath' filesep 'inputfile.csv']
Read the file
datafile = csvread(filepath)
Otherwise go with Amros answer. It is simpler.