Home > Software design >  How To Filter a Matlab Array of Structs Based Upon The Value Of A Struct field Of Type String
How To Filter a Matlab Array of Structs Based Upon The Value Of A Struct field Of Type String

Time:09-29

I've made an array of structs that contains every file & dir in my parent directory, using

allfiles = dir(fullfile('.',"**"));.

However, I'm only interested in files named 'data.env'.

My belief is that the name of every file in the directory tree is contained in the 'name' field of some row of allfiles and the path to each file is contained in the 'folder' field. How can I remove all rows from all files, where the name field is not 'data.env'?

My best attempt has been as follows:

ctr=0;
loclist = [];
for ii = 1:size(allfiles)
  if strcmp(allfiles(ii).name,'data.env')
    loclist(ctr 1)=ii;
    ctr=ctr 1;
  end
end
relevantFiles=allfiles(loclist);

but, I'm certain there's a more elegant solution that vectorizes my for loop.

CodePudding user response:

You could generate a logical index vector with arrayfun and use that to create the result. E.g.,

x = arrayfun(@(k)strcmp(allfiles(k).name,'data.env'),1:numel(allfiles));
relevantFiles = allfiles(x);
  • Related