How to search and sort strings from a structure efficently?

6 views (last 30 days)
Lets say I have one structure with file names as character arrays (strings). Some file names have Z1P in them, Z1G, or Z1K. Other's might not. What I am trying to do is sort this structure (Called Dat.standard.name) by these files names, into a separate structure with the strings that I am looking for as fields. So from the Dat.standard.name, the unsorted data gets sorted into a structure called Sort.standard.Z1P for any files that have Z1P in them, Sort.standard.Z1G for any files that have Z1G in them and so on. Any ideas on how to go about this in the most efficient manner?

Accepted Answer

Stephen23
Stephen23 on 11 May 2017
Edited: Stephen23 on 11 May 2017
Dat.standard(1).name = 'x';
Dat.standard(2).name = 'xZ1P';
Dat.standard(3).name = 'x';
Dat.standard(4).name = 'xZ1G';
Dat.standard(5).name = 'x';
Dat.standard(1).data = 1;
Dat.standard(2).data = 2;
Dat.standard(3).data = 3;
Dat.standard(4).data = 4;
Dat.standard(5).data = 5;
C = {'Z1P','Z1G','Z1K'};
S = Dat.standard;
fun = @(s)cellfun('isempty',regexp(s,C,'once'));
idx = cellfun(@(s)any(~fun(s)),{S.name});
Srt.standard = S(idx);
Where Srt.standard contains a structure array which is a subset of Dat.standard, where the names contain any of the strings in C.
Note: in general you should store your data in the simplest array/structure possible. In this case nested structures do not make working with your data simpler, but actually make it more complicated. It might be worth considering if you could simplify the data organization somehow.
  1 Comment
Ibro Tutic
Ibro Tutic on 11 May 2017
Edited: Ibro Tutic on 11 May 2017
The reason for the nested structure is because I have these same files for multiples tests with different parameters. The intention is to get a single structure, with the data from each of the the Z1G, Z1P, etc files for each test. I plan on saving these structures off as MAT files and then all of the data is available in one easy to find place. If you have any recommendations for methods that may be easier I would be happy to try them.
The data itself is stored in these files. I am not working with any data besides the filenames themselves. My intention was to sort all of the data first, and then pull it into the structure. To avoid working with millions of numbers and moving them from structure to structure.

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!