matlab - Pull specific cells out of a cell array by comparing the last digit of their filename -


i have cell array of filenames - things '20160303_144045_4.dat', '20160303_144045_5.dat', need separate separate arrays last digit before '.dat'; 1 cell array of '...4.dat's, 1 of '...5.dat's, etc.

my code below; uses regex split file around '.dat', reshapes bit regexes again pull out last number of filename, builds cell store filenames in then, , tad stuck. have array produced such '1,0,1,0,1,0..' of required cell indexes thought might trivial pull out, i'm struggling want.

numfiles = length(samplefile); %samplefile input cell array  splitfiles = regexp(samplefile,'.dat','split'); column = vertcat(splitfiles{:}); column = column(:,1);  splitnums = regexp(column,'_','split'); splitnums = splitnums(:,1); column = vertcat(splitnums{:}); column = column(:,3);  column = cellfun(@str2double,column); %produces column array of values - 3,4,3,4,3,4, etc  uniquevals = unique(column); numchannels = length(uniquevals);   filenamecell = cell(ceil(numfiles/numchannels),numchannels);  = 1:numchannels     column(column ~= uniquevals(i)) = 0;    column = column / uniquevals(i); %e.g. 1,0,1,0,1,0     %filenamecell(i)  end 

i feel there should easier way hodge-podge of code, , don't want throw ton of messy for-loops if can avoid it; believe i've overcomplicated problem massively.

we can neaten code quite bit.

take example data:

files = {'abc4.dat';'abc5.dat';'def4.dat';'ghi4.dat';'abc6.dat';'def5.dat';'nonum.dat'}; 

you can final numbers using regexp , matching 1 or more digits followed '.dat', using strrep remove '.dat'.

filenums = cellfun(@(r) strrep(regexp(r, '\d+.dat', 'match', 'once'), '.dat', ''), ...                    files, 'uniformoutput', false); 

now can put these in structure, using unique numbers (prefixed letter because fields can't start numbers) field names.

% unique file numbers , set output struct ufilenums = unique(filenums); filestruct = struct; % loop on file numbers ii = 1:numel(ufilenums)     % files have number     idx = cellfun(@(r) strcmp(r, ufilenums{ii}), filenums);     % assign identified files struct field     filestruct.(['x' ufilenums{ii}]) = files(idx); end 

now have neat output

% files numbers before .dat given field in output struct filestruct.x4 = {'abc4.dat' 'def4.dat' 'ghi4.dat'} filestruct.x5 = {'abc5.dat' 'def5.dat'} filestruct.x6 = {'abc6.dat'} % files without numbers before .dat captured filestruct.x =  {'nonum.dat'} 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -