Question

I have a cell array with strings and a numeric array in Matlab. I want every entry of the cell array to be concatenated with the number from the corresponding position of the array. I think that it can be easily solved using cellfun, but I failed to get it to work.

To clarify, here is an example:

c = {'121' '324' '456' '453' '321'};
array = 1:5

I would like to get:

c = {'1121' '2324' '3456' '4453' '5321'}
Was it helpful?

Solution

A special version of sprintf that outputs directly to a cell array is called sprintfc:

>> C = sprintfc('%d%d',[array(:) str2double(c(:))]).'
C = 
    '1121'    '2324'    '3456'    '4453'    '5321'

It is also a bit different in the way it handles array inputs, by preserving the shape.

OTHER TIPS

You're correct, you can use cellfun – you just need to convert the array to a cell array as well using num2cell. Assuming array is a vector of integers:

c = {'121' '324' '456' '453' '321'};
array = 1:5;
c2 = cellfun(@(c,x)[int2str(x) c],c,num2cell(array),'UniformOutput',false)

which returns

c2 = 

    '1121'    '2324'    '3456'    '4453'    '5321'

In your case, you can also accomplish the same thing just using cell2mat and mat2cell:

c2 = mat2cell([int2str(array(:)) cell2mat(c.')],ones(1,length(array))).'

Another one-liner, this one without undocumented functions (with thanks to @chappjc for showing me the "format" input to num2str):

strcat(num2str(array(:),'%-d'),c(:)).'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top