Search code examples
stringmatlabconcatenationmatlab-uitable

Is it possible to concatenate a string with series of number?


I have a string (eg. 'STA') and I want to make a cell array that will be a concatenation of my sting with a numbers from 1 to X.

I want the code to do something like the fore loop here below:

for i = 1:Num
    a = [{a}  {strcat('STA',num2str(i))}]
end

I want the end results to be in the form of {<1xNum cell>}

a = 'STA1' 'STA2' 'STA3' ...

(I want to set this to a uitable in the ColumnFormat array)

ColumnFormat = {{a},...                 % 1
             'numeric',...              % 2
             'numeric'};                % 3

Solution

  • You can do it with combination of NUM2STR (converts numbers to strings), CELLSTR (converts strings to cell array), STRTRIM (removes extra spaces)and STRCAT (combines with another string) functions.

    You need (:) to make sure the numeric vector is column.

    x = 1:Num;
    a = strcat( 'STA', strtrim( cellstr( num2str(x(:)) ) ) );
    

    As an alternative for matrix with more dimensions I have this helper function:

    function c = num2cellstr(xx, varargin)
    %Converts matrix of numeric data to cell array of strings
    
    c = cellfun(@(x) num2str(x,varargin{:}), num2cell(xx), 'UniformOutput', false);