How to combine struct names based on the first 'n' characters of name

2 views (last 30 days)
I'm handling a great amount of test data, i import the filenames by using:
files = dir('*.xls');
After handling the data i end up with the 'files.name' list and a 'n x 1 matrix' which list a result:
Object1_test1.xls 3
Object1_test2.xls 6
Object2_test1.xls 4
Object3_test1.xls 5
I'm seeking a way to combine the data for each object (based on the first 'n' characters of the name) as seen below:
Object1 9
Object2 4
Object3 5

Answers (1)

Stephen23
Stephen23 on 11 Nov 2020
Edited: Stephen23 on 11 Nov 2020
One approach:
fnm = {'Object1_test1.xls','Object1_test2.xls','Object2_test1.xls','Object3_test1.xls'};
val = [3,6,4,5];
tmp = regexp(fnm,'^[^_]+','once','match');
[unf,~,idx] = unique(tmp);
out = accumarray(idx,val(:))
out = 3×1
9 4 5
If you need to perform this operation for several variables, put the data into one table and use the split-apply-combine workflow.

Categories

Find more on File Operations in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!