Using strjoin on each row of NxM cell array

36 views (last 30 days)
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!

Accepted Answer

Stephen23
Stephen23 on 16 Dec 2021
C = {'ABC','123','blue';'DEF','456','red';'GHI','789','green'}
C = 3×3 cell array
{'ABC'} {'123'} {'blue' } {'DEF'} {'456'} {'red' } {'GHI'} {'789'} {'green'}
D = cellfun(@(v)join(v,'_'),num2cell(C,2))
D = 3×1 cell array
{'ABC_123_blue' } {'DEF_456_red' } {'GHI_789_green'}
  2 Comments
Bryan Wilson
Bryan Wilson on 16 Dec 2021
Thanks, works great! Can you explin why num2cell is used here? I see that it's changing the array from NxM to Nx1 of 1xM, but I don't understand what's happening beind the scenes.
Stephen23
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!