Search code examples
arraysmatlabcharpaddingpad

padding char array to a specific size matlab


if I have char array,ex: A='hello' of size 5 chars and I want to pad it with another character or set of characters to make its size =16 how can I pad this array in matlab ? and what should I use for padding can I use zero or I must use another character ?


Solution

  • You can use sprintf:

    result = sprintf('%-16s','hello');
    

    Or it can be created using array concatenation:

    ex = 'hello';
    result = [ex blanks(16-length(ex))];
    

    Padding with other characters(e.g. 'a'):

    ex = 'hello';
    result = [ex repmat('a',1,16-length(ex))];
    

    *As of MATLAB R2016b you can use pad function.