Search code examples
stringmatlabcell-array

Matlab, how to write two number variables into single string cell array variable?


I have two number variables of size <5x1>

    X = [ 1, 2, 3, 4, 5]';
    Y = [-1, -2, 4.5, 12.6, -5]';

and I would like to write a variable string cell array <5x1 cell> using these X and Y variables with output as

'     1,-1,'
'     2,-2,'
'     3,4.5,'
'     4,12.6,'
'     5,-5'

Any help will be appreciative. Thanks


Solution

  • I think this is the most intuitive and fastest way:

    %# example data
    X = [ 1, 2, 3, 4, 5]';
    Y = [-1, -2, 4.5, 12.6, -5]';
    
    %# Controls the amount of leading spaces. This may depend on your specific 
    %# software (or hardware?) so I left it here as a seperate variable.
    spaces = {repmat(' ', 1,5)};  %# NOTE: must be cell to protect it from trim()
    
    %# Now form the cellstring
    S = strcat(spaces, num2str(X), ',', num2str(Y, '%-g'), ',');
    
    %# complete it by removing the last comma
    S{end} = S{end}(1:end-1);