Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cell array, add suffix to every string

Suppose I have a cell array containing strings:

c = {'foo1', 'foo2', 'foo3'}

I now want to add the same suffix "bar" to each string, such that the cell array becomes:

c = {'foo1bar', 'foo2bar', 'foo3bar'}

Is there a shortcut to doing this, without explicitly looping through each element?

like image 797
Karnivaurus Avatar asked Dec 11 '22 07:12

Karnivaurus


2 Answers

strcat operates on cell arrays:

>> c = {'foo1', 'foo2', 'foo3'}
c = 
    'foo1'    'foo2'    'foo3'
>> c2 = strcat(c,'bar')
c2 = 
    'foo1bar'    'foo2bar'    'foo3bar'
like image 160
chappjc Avatar answered Dec 24 '22 14:12

chappjc


What about using cellfun:

c=cellfun(@(x) strcat(x, 'bar'), c, 'Uniformoutput', 0);

I don't know if it's faster to run than a loop, but it's less tedious to write.

Edit: apparently strcat handles cell arrays. Use cellfun for functions that don't.

like image 45
Cape Code Avatar answered Dec 24 '22 13:12

Cape Code