How do I concatenate a variable number of cell arrays
3 views (last 30 days)
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
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.
Answers (0)
See Also
Categories
Find more on Logical 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!