How to apply MATLAB addpath to non static string? - matlab

dir1 = '/tmp1';
dir2 = '/tmp2'
If we do the following
addpath [dir1 dir2];
MATLAB takes '[dir1 dir2]' as the path name to add. We can do the following
eval(sprintf(...
'addpath %s;', ...
[dir1 dir2]));
I was wondering if there is any better way. Thank you,

A very simple way to achieve what you want is to call:
addpath(fullfile(dir1,dir2));
Fullfile will take care of adjusting the string to be a proper folder name (under both Windows and Unix) as in:
fullfile('foo','bar') % returns foo/bar
fullfile('foo/','bar') % returns foo/bar
To add files recursively just do:
pathsToAdd = genpath(fullfile(dir1,dir2));
addpath(pathsToAdd);

The general issue that you are having is that MATLAB has two ways of calling commands. The first does not use an explicit function call function() but rather just multiple inputs on the command line separated by a space:
addpath directory1 directory2
As you know this will add both directory1 and directory2 to the path.
What is happening here is that MATLAB converts all of the inputs to strings implicitly and passes them to the addpath function. The explicit equivalent is
addpath('directory1', 'directory2')
As you can see, internally MATLAB calls addpath like a normal function with input parameters, and as such you can pass it variables rather than string literals:
dir1 = 'directory1';
dir2 = 'directory2';
addpath(dir1, dir2);
This is why you are seeing an issue with:
addpath [dir1 dir2]
Because, as written, [dir1 dir2] is convert to a string (implicitly) since it was passed using the function parameter1 parameter2 syntax rather than the explicit function syntax.
Also, be careful because [dir1, dir2] doesn't do what you think it does. What it actually does it appends the strings dir1 and dir2 and would result in:
[dir1, dir2]
/tmp1/tmp2
If that is what you expect, then use fullfile rather than basic horizontal concatenation to ensure you have the proper file separators, etc.
addpath(fullfile(dir1, dir2));
You will actually see the implicit syntax in many MATLAB functions that accept only strings as input parameters. It is important to know, though, that you can always use the explicit function call function() instead to pass input strings which may be stored in variables.

Related

Matlab: set current working directory as top priority in path

In one of my projects, I have a Matlab function called eom.m. When I try to call it, I get errors. I have realised this is because Matlab calls a simulink file, eom.slx, instead, which is in one of the toolboxes.
I would prefer not to rename the function, so I was wondering how I could change the order in the Matlab path so that the folder I call Matlab from always has top priority. That is to say how I can ensure that the files in my current working directory are always those that are called in fact.
Thank you for the help!
You can do it programmatically using addpath with the '-begin' option.
You can use command syntax:
addpath c:/path/you/want -begin
Enclose with quotes if the path contains spaces:
addpath 'c:/path /you/ want' -begin
Alternatively, you can use function syntax:
addpath('c:/path/you/want', '-begin')
This allows having the path stored in a variable:
p = 'c:/path/you/want';
addpath(p, '-begin')

Warning Control Character '\S' is not valid when concatinating two strings

I have two variables such as:
path='data\voc11\SegmentationClassExt\%s.png'
name='123'
I want to concatenate two strings into one like so:
data\voc11\SegmentationClassExt\123.png
I used the code below:
sprintf(path, name)
However I receive the following error:
Warning: Control Character '\S' is not valid. See 'doc sprintf' for control characters valid in the format string.
ans =
dataoc11
I am using MATLAB on Windows. Could you give me any solution for that. I tried to change path='data\\voc11\\SegmentationClassExt\\%s.png' and when I did that, the above code will work. However, the current data is
path='data\voc11\SegmentationClassExt\%s.png';
use the matlab function fullfile
filename = fullfile ( path, [name '.png'] );
or
filename = fullfile ( path, sprintf ( '%s.png', name ) );
Note: you should avoid using path as a variable as it is already a Matlab function
Before we start, it's highly advised that you do not use path as a local variable. path is a global variable that MATLAB uses to resolve function scope, especially if you are going to use any functions from toolboxes. Overwriting path with your own string will actually make MATLAB not function properly. Use a different variable name.
Now to resolve your problem, you can use either fullfile as what #matlabgui has suggested, or if you don't care about OS compatibility and are only working in Windows, you can either manually change the path as you have placed so that you can introduce two back slashes and it will indeed work on Windows OS, or you can perhaps use a string replace function so that all back slashes will be accompanied with an additional back slash.
Either one of these two methods will work:
Method 1 - Using regular expressions
pat = 'data\voc11\SegmentationClassExt\%s.png';
pat_new = regexprep(pat, '\\', '\\\\');
The function regexprep performs a string replacement by regular expressions. We search for all single backslashes and replace them with double backslashes. Note that the single back slash \ is a special character in regular expressions so if you explicitly what to look for back slashes, you must place an additional back slash beside it.
Method 2 - Using strrep
pat = 'data\voc11\SegmentationClassExt\%s.png';
pat_new = strrep(pat, '\', '\\');
strrep stands for String Replace. It works very similar to regular expressions as we have discussed above. However, what's nice is that you don't have to append an additional back slash when looking for the actual character.
Once you do this, you can use sprintf as normal:
pat_new = sprintf(pat_new, name);

Store user input as wildcard

I am having some trouble with a data processing function in MATLAB. The function takes the name of the file to be processed as an input, finds the desired files, and reads in the data.
However, several of the desired files are variants, such as Data_00.dat, Data.dat, or Data_1_March.dat. Within my function, I would like to search for all files containing Data and condense them into one usable file for processing.
To solve this, I would like desiredfile to be converted into a wildcard.
Here is the statement I would like to use.
selectedfiles = dir *desiredfile*.dat % Search for file names containing desiredfile
This returns all files containing the variable name desiredfile, rather than the user input.
The only solution that I can think of is writing a separate function that manually condenses all the variants into one file before my function is run, but I am trying to keep the number of files used down and would like to avoid this.
You could concatenate strings for that. Considering desiredFile as a variable.
desiredFile = input('Files: ');
selectedfiles = dir(['*' desiredfile '*.dat']) % Search for file names containing desiredfile
Enclosing strings between square brackets [string1 string2 ... stringN]concatenates them. Matlab's dir function receives a string.
I believe you can achieve that using the dir command.
dataSets = dir('/path/to/dir/containing/Data*.dat');
dataSets = {dataSets.name};
Now simply loop over them, more information here.
To quote the matlab help:
dir lists the files and folders in the MATLABĀ® current folder. Results appear in the order returned by the operating system.
dir name lists the files and folders that match the string name. When name is a folder, dir lists the contents of the folder. Specify name using absolute or relative path names. You can use wildcards (*).

read function from text file in matlab

I'm going to read some function from a Unicode text file in matlab and calculate there answer with my own variables. first i use fopen to read the text file, then what should i do to convert each line of that text file to a function? for example the func.txt contains:
(x^2)-3y
sin(x+z)+(y^6)
and i need to write an m.file which read func.txt and process that like this:
function func1[x,y] = (x^2)-3y
function func2[x,y,z] = sin(x+z)+(y^6)
Preamble: if your final aim is to use those functions in matlab (i.e. evaluate them for some values of x,y,...), I would rather suggest the following approach that looks more robust to me.
In principle, in fact, you don't need to manipulate the file funct.txt to evaluate the functions defined therein.
First problem: each line of your file funct.txt must define an inline function.
Say that the first function (i.e., the first line) of the file funct.txt has been copied into a string str,
str = '(x^2)-3y',
you can obtain a function from it using the command inline:
f1 = inline(str,'x','y');
which gives to you (matlab output)
f1 =
Inline function:
f1(x,y) = (x^2)-3y.
Now you can use f1 just calling it as f1(x,y), for whatever values x,y.
Second problem: you have to parse your file funct.txt to obtain the strings str containing the definitions of your functions. That's easier, you may want to consider the function fgets.
Third problem: the functions in funct.txt may depend on 2,3 (or more?) independent variables. As far as I know there is no easy way to parse the string to discover it. Thus, you may want to define each inline function as depending on all your independent variables, i.e.
f1 = inline('(x^2)-3y','x','y','z');
the variable z will play no active role, by the way. Nonetheless, you need to specify a third dummy parameter when you call f1.

Issue on writing a function with string as the argument

I need to write a function whose input argument should be file name, and the function will perform certain operation on the opened file. Here is the sample function I wrote,
function readFile = loadOneColumnFile(fileName)
fid1 = fopen(fileName);
readFile = 0;
fclose(fid1);
But when I invoke this function in the command console as follows,
>> testValue = loadOneColumnCSV('/usr1/test.csv');
The Matlab returns the following error message
??? Undefined function or method 'loadOneColumnFile' for input arguments of type 'char'.
Looks like that the definition of function is not correct. How to fix it? Thanks.
MATLAB treats a string as an array of characters (like C++, except the strings are not null-terminated in MATLAB).
Despite the error message, I don't think there is any problem with the string passing. The problem is MATLAB cannot find your function. So:
The file containing the function must have same name as the function (in your case save the function in a file named loadOneColumnFile.m)
The loadOneColumnFile.m must be placed in the working (current) directory so MATLAB could find it.
The name of the function is not consistent in your question. Make sure you have used only one of the loadOneColumnFile or loadOneColumnCSV for naming the function and filename.