Using strjoin on each row of NxM cell array
36 views (last 30 days)
Show older comments
I have NxM cell arrays of text and I need to use strjoin across each row, with an underscore as the delimiter. I think I need cellfun or rowfun, but I can't figure out the syntax.
C = [{'ABC'} {'123'} {'blue'};
{'DEF'} {'456'} {'red'};
{'GHI'} {'789'} {'green'}]
C_join = rowfun(@strjoin,C,'_');
The goal is a Nx1 cell array of joined text...
C_join = [{'ABC_123_blue'};
{'DEF_456_red'};
{'GHI_789_green'}]
Thanks for you help!
0 Comments
Accepted Answer
Stephen23
on 16 Dec 2021
C = {'ABC','123','blue';'DEF','456','red';'GHI','789','green'}
D = cellfun(@(v)join(v,'_'),num2cell(C,2))
2 Comments
Stephen23
on 16 Dec 2021
Edited: Stephen23
on 16 Dec 2021
NUM2CELL splits any array (not just numeric ones) into separate arrays in one cell array. By default it splits every element into a scalar array, but the optional second argument lets the user specify any dimensions to "keep together". I used that in my answer to give the Nx1 cell array containing 1xM cell vectors (i.e. the 2nd dimension was "kept together"). That Nx1 cell array is supplied to CELLFUN, which calls an anonymous function N times, each time with the content of one cell, i.e. one 1xM cell vector. The anonymous function does whatever you tell it to do with that 1xM cell vector and returns the result. Cellfun collects those results back into one array (the same size as its input) and returns that as its output.
More Answers (0)
See Also
Categories
Find more on Characters and Strings 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!