Search This Blog

Thursday, February 21, 2013

append a number to a string in matlab

Problem: Given a prefix say 'foo', generate a cell array of strings in Matlab such that each string has a number appended to it.

Ans:
>> n=5; cas = cellstr([repmat('foo', n, 1), num2str([1:n]')])

cas = 

    'foo1'
    'foo2'
    'foo3'
    'foo4'
    'foo5'
 Spaces are automatically appended when the appended numbers have wider range.
>> n=10; cas = cellstr([repmat('foo', n, 1), num2str([1:n]')])

cas = 

    'foo 1'
    'foo 2'
    'foo 3'
    'foo 4'
    'foo 5'
    'foo 6'
    'foo 7'
    'foo 8'
    'foo 9'
    'foo10'
Adding another string at the top of the array is easy
>> n=10; cas = [{'raju'}; cellstr([repmat('foo', n, 1), num2str([1:n]')])]

cas = 

    'raju'
    'foo 1'
    'foo 2'
    'foo 3'
    'foo 4'
    'foo 5'
    'foo 6'
    'foo 7'
    'foo 8'
    'foo 9'
    'foo10'
which can also be done by
>> n=10; cas = cellstr([repmat('foo', n, 1), num2str([1:n]')]); cas2 = [{'raju'}; cas]

cas2 = 

    'raju'
    'foo 1'
    'foo 2'
    'foo 3'
    'foo 4'
    'foo 5'
    'foo 6'
    'foo 7'
    'foo 8'
    'foo 9'
    'foo10'

No comments:

Followers