Monday, February 15, 2010

Composing a string and executing it in Matlab : preserving empty spaces

Say you want to automatically open files which are named file001, file002, etc. Further suppose that these files are in a folder named d:\folder 1, d:\folder 2, etc.
Normally, you could use strcat to concatenate a string together with num2str. For example
FILE = strcat('file00',num2str(i));
But strcat will eliminate empty spaces so if strcat is used this way,
FOLDER = strcat('folder ',num2str(3)); % note the single space after 'folder'
the result will be
FOLDER ='folder3'.
To preserve the empty space, use square brackets instead:
FOLDER = ['folder ',num2str(3)]
Suppose you composed a string containing a command:
com1 = 'cd c:\folder 3\file001.jpg'
To execute the string use exec:
exec(com1);


No comments: