How do I concatenate a variable number of cell arrays
Show older comments
I want to combine a variable number of cell arrays into one large array. I was thinking of using this:
combined_data = {};
for k = 1 : length(raw_data)
combined_data = [combined_data ; raw_data{k}.vdata(3:raw_data{k}.empties,:)];
end
I thought I read somewhere that creating an array by concatenating itself is bad form. I never see examples like this.
Is the above good or bad form?
If bad, is there an alternative?
8 Comments
Star Strider
on 18 Nov 2022
I am not certain what you want.
Mathieu NOE
on 18 Nov 2022
well , it's not a crime by itself but purists would tell you it's better to preallocate memory ,so create combined_data array first with the correct dimensions and then paste the new data (RHS) to combined_data (with correct start / end indexes)
there could still be one case where this code is making sense : when the new data have unpredictable length, so in that case it might be difficult to preallocate the right amount or rows / columns (unless you overestimate it)
my 2 cents
Ted HARDWICKE
on 18 Nov 2022
"'raw_data' is a cell array with 5 structs in it. "
Rather than a non-scalar cell array containing lots of scalar structures, you should probably just use one non-scalar structure array. That would simplify the task somewhat.
After that, you can probably achieve most of what you want with judicious use of a few comma-separated lists:
Why does this loop start at 3?:
for r = 3:raw_data{k}.empties
Hopefully not for this reason: https://www.mathworks.com/matlabcentral/answers/484430-using-struct-dir-selpath-what-do-and-mean-as-struct-name
Ted HARDWICKE
on 18 Nov 2022
I presume that FILES_STRUCT is the structure returned by DIR, in which case it is already a container array of the exactly the right size, so you can just use that (rather than creating even more container arrays):
for k = 1:numel(Files_struct)
S = load(Files_struct(k).name); % Got rid of the superfluous square brackets too.
X = find(cellfun(@isempty,S.vdata(:,1)));
Files_struct(k).rawdata = S;
Files_struct(k).empties = X(1)-1;
end
You can access the elements of the structure using perfectly normal indexing, e.g. the 2nd file:
Files_struct(2).name % filename
Files_struct(2).rawdata % loaded data
Files_struct(2).empties % etc.
I would recommend not working with nested structures, so after the loop you might want to do this:
data = [Files_struct.rawdata] % assumes every MAT file has the same variable names.
to make it easier to access the loaded data.
Ted HARDWICKE
on 21 Nov 2022
Answers (0)
Categories
Find more on Cell Arrays 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!