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일
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 Exchange에서 Characters 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