Search code examples
matlabsymbolscell-array

Concatenate symbol with cell array values in Matlab


I have a cell of double {52x1}, I would like to concatenate to each element the symbol ±.

The problem I am having is that sprintf doesn't support the Matlab code \pm for calling the symbol.

Any help is welcome!


Solution

  • \pm is a TeX/LaTeX command, which gives ± only if the interpreter used by Matlab understands LaTex. This occurs for example in axis labels when the TickLabelInterpreter property is set to 'tex'.

    In sprintf you can directly use the ± symbol (code point 177). For example,

    x = num2cell(rand(5,1)); % cell array of numbers
    sprintf('±%f\n', [x{:}])
    

    or

    sprintf([177 '%f\n'], [x{:}])
    

    gives

    ans =
    ±0.126987
    ±0.913376
    ±0.632359
    ±0.097540
    ±0.278498
    

    Note that I had to transform the cell array of numbers to a numeric vector in order to pass it to sprintf. Consider defining the data directly as a numeric vector to avoid that step.


    If you want a cell array of strings as result:

    cellfun(@(t) sprintf([177 '%f\n'], t), x, 'UniformOutput', false)