Using strjoin on each row of NxM cell array

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!

 採用された回答

Stephen23
Stephen23 2021 年 12 月 16 日

1 投票

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 件のコメント

Bryan Wilson
Bryan Wilson 2021 年 12 月 16 日
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 2021 年 12 月 16 日
編集済み: Stephen23 2021 年 12 月 16 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

製品

リリース

R2020b

質問済み:

2021 年 12 月 16 日

編集済み:

2021 年 12 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by