MATLABUnicodePath

From WikiMEG
Revision as of 11:17, 10 November 2014 by Duke (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Sometimes odd characters or characters with accents prevent MATLAB from opening a file, even if you copy the filename directly from Windows explorer: "04%10%08@1443"

We can use a short function to retrieve a list of all files in a certain folder:

function contents = dir2(path, filter, ignore_dot)
%
% dir2 list contents on path recursively, using java.io.File, so 
% weird characters are converted correctly to MATLAB usuable 
% path names.
%
% filter - string, expression used to filter file names
% ignore_dot - ignore files and folders beginning with .
%
% mw 10 11 2014 - creation
 
if nargin < 2, filter = '.*'; end
if nargin < 3, ignore_dot = 1; end
 
f = java.io.File(path);
fs = f.listFiles();
contents = {};
for i=1:length(fs)
    fname = fs(i).getName().toCharArray()';
    abspath =  fs(i).getCanonicalPath().toCharArray()';
    if ignore_dot && fname(1) == '.'
        continue
    end
    if fs(i).isDirectory()
        subcontents = dir2(abspath, filter, ignore_dot);
        contents = {contents{:} subcontents{:}};
    end
    match = regexp(fname, filter, 'ONCE');
    if match
        contents = {contents{:} abspath};
    end
end

The resulting list of files can be filtered with a regular expression, so that you have exactly the files you're looking for:

>> path = 'Y:\MEG\DATA\Protocoles_epilepsie\epil\epil_003\cont3mtr';
>> re = 'c,rf.*Hz$';
>> fs = dir2(path, re);

Here, the regex says find filenames starting with "c,rf", then any character, then "Hz" then end of line "$". We can check the results:

>> for i=1:length(fs), fprintf('%s\n', fs{i}); end
Y:\MEG\DATA\Protocoles_epilepsie\epil\epil_003\cont3mtr\03%11%08@1035\1\c,rfhp1.0Hz
Y:\MEG\DATA\Protocoles_epilepsie\epil\epil_003\cont3mtr\03%11%08@1035\2\c,rfhp1.0Hz
Y:\MEG\DATA\Protocoles_epilepsie\epil\epil_003\cont3mtr\03%11%08@1035\3\c,rfhp1.0Hz
Y:\MEG\DATA\Protocoles_epilepsie\epil\epil_003\cont3mtr\03%11%08@1035\4\c,rfhp1.0Hz
Y:\MEG\DATA\Protocoles_epilepsie\epil\epil_003\cont3mtr\03%11%08@1035\5\c,rfhp1.0Hz