Search code examples
stringvectortype-conversionoctave

Octave: How to turn a vector of integers into a cell array of strings?


In Octave:

Given a vector

a = 1:3

How to turn vector "a" into a cell array of strings

{'1','2','3'}

(Output of this:)

ans =
{
  [1,1] = 1
  [1,2] = 2
  [1,3] = 3
}

(question end)


Further information: my aim is to use a as the input of strcat('x',a) to get

ans =
{
  [1,1] = x1
  [1,2] = x2
  [1,3] = x3
}

Other solutions how to reach this aim are welcome, but the main question is about getting an array of strings directly from a vector.

This question is a follow-up from cell array, add suffix to every string which could not help me, since strcat('x',{'1','2','3'}) works, but strcat('x', num2cell(1:3)) does not:

>> strcat('x', num2cell(1:3))
warning: implicit conversion from numeric to char
warning: called from
    strcat at line 121 column 8
    C:/Users/USERNAME/AppData/Local/Temp/octave/octave_ENarag.m at line 1 column 1

warning: implicit conversion from numeric to char
warning: called from
    strcat at line 121 column 8
    C:/Users/USERNAME/AppData/Local/Temp/octave/octave_ENarag.m at line 1 column 1

warning: implicit conversion from numeric to char
warning: called from
    strcat at line 121 column 8
    C:/Users/USERNAME/AppData/Local/Temp/octave/octave_ENarag.m at line 1 column 1

ans =
{
  [1,1] = x[special sign "square"]
  [1,2] = x[special sign "square"]
  [1,3] = x[special sign "square"]
}

Also, the Matlab function string(a) according to Matlab: How to convert cell array to string array?, is not yet implemented:

"The 'string' function is not yet implemented in Octave.`


Solution

  • You can combine cellstr and int2str:

    strcat('x', cellstr(int2str((1:3).')))
    or
    cellstr(strcat('x', int2str((1:3).')))
    

    You can also combine sprintf and ostrsplit:

    ostrsplit(sprintf('x%d ', 1:3), ' ', true)
    or
    strcat('x', ostrsplit(sprintf('%d ', 1:3), ' ', true))
    

    You can also use num2str instead of int2str.