How do I concatenate a variable number of cell arrays

3 views (last 30 days)
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
Stephen23
Stephen23 on 18 Nov 2022
Edited: Stephen23 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
Ted HARDWICKE on 21 Nov 2022
I revised my script that processes the field data to produce a table instead of an array, and incporporated your suggestions with a couple of changes: " ... = S.vdatat" instead of "... = S". This would allow the access methods you suggest. The second taking advantage of table variable names - 'Site' instead of {:,1}.
Thanks for the help.
for k = 1:numel(Files_struct)
S = load(Files_struct(k).name);
X = find(cellfun( @isempty,S.vdatat.site )); %isempty requires a cell array. using a datetime will fail as it is naT
Files_struct(k).vdata = S.vdatat; % ** ** **
Files_struct(k).empties = X(1)-1;
end

Sign in to comment.

Answers (0)

Tags

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!