I'm reading in a mat file which has variables with a counter e.g. a1
, a2
, a3
, b
, c1
and c2
.
I want to put the data into a structure with field names "a", "b" and "c" where
a=[a1;a2;a3]
, b=b
and c = [c1; c2]
.
The algorithm needs to be able to do this, without knowing what the maximum value of the counter of each variable is. How can I do this?
First, you would load your mat file data using the
load
function, placing it in a structure. Let's say that gave you the following sample data:Then, we'll order the fields alphabetically using
orderfields
, find the field names usingfieldnames
, useregexprep
to strip all trailing numbers off of the field names, then get the unique substrings usingunique
:Using the indices returned by
unique
, we can calculate how many times each substring appears by doingdiff([0; inds])
. Then, we group the structure data into a cell array using these counts andstruct2cell
andmat2cell
:Notice that we have a cell array of cell arrays. If you know for sure that each set of entries for each substring will concatenate properly (as in our example), you can concatenate them using
cellfun
andcell2mat
as follows:Now we have a cell array of matrices, and a new structure can be made using
cell2struct
: