cell array, add suffix to every string

半世苍凉 提交于 2021-01-27 07:32:04

问题


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?


回答1:


strcat operates on cell arrays:

>> c = {'foo1', 'foo2', 'foo3'}
c = 
    'foo1'    'foo2'    'foo3'
>> c2 = strcat(c,'bar')
c2 = 
    'foo1bar'    'foo2bar'    'foo3bar'



回答2:


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.



来源:https://stackoverflow.com/questions/22462855/cell-array-add-suffix-to-every-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!