How to append a large number of cell arrays vertically?
2 views (last 30 days)
Show older comments
Hi all,
I have a large number of cell arrays that I need to append all of them vetically into a unique cell array. I do not want to load each of cell array individually and then append all of them. Can anyone tell me how I can do it in the most efficient way?
Thanks in advance for your asnwers.
2 Comments
the cyclist
on 19 Mar 2023
We need more information. How are the individual cell arrays stored? (For example, are all the cell arrays already in the workspace, or do they need to be loaded from MAT files?) How are they named? For example, if your cell variables are named cellFred, cellWilma, cellBarney, and cellBetty, then there is no choice but to name them each individually to append them:
bigCell = [cellFred; cellWilma; cellBarney; cellBetty];
But maybe they have some naming convention that helps.
Are you just trying to avoid typing all the names? I mean, there isn't really a command for "append all files" that isn't somehow naming all the files to be appended.
Accepted Answer
Matt J
on 19 Mar 2023
Edited: Matt J
on 19 Mar 2023
s=dir('stations_*.mat');
CellList=cellfun(@(z) load(z).stations1,{s.name},'uni',0);
result=vertcat(CellList{:})
3 Comments
Matt J
on 19 Mar 2023
z is the name I've chosen for the input to the function,
fun=@(z) load(z).stations1
the cyclist
on 19 Mar 2023
Edited: the cyclist
on 19 Mar 2023
Just to expand @Matt J's answer a bit. He used an anonymous function to accomplish the task. z is a dummy variable that will be substituted out by the values in the cell array (from the second argument to cellfun).
A simple example of an anonymous function is
func_sqr = @(x) x.^2
func_sqr([2 3 5])
You can see that x (like z in Matt's example) is just a placeholder variable in the function definition.
More Answers (0)
See Also
Categories
Find more on Function Creation 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!