【问题标题】:Octave: How to turn a vector of integers into a cell array of strings?Octave:如何将整数向量转换为字符串元胞数组?
【发布时间】:2021-01-04 16:45:54
【问题描述】:

八度:

给定一个向量

a = 1:3

如何将向量“a”转换为字符串元胞数组

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

(这个的输出:)

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

(问题结束)


更多信息:我的目标是使用 a 作为strcat('x',a) 的输入来获取

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

欢迎使用其他实现此目标的解决方案,但主要问题是直接从向量中获取字符串数组。

这个问题是cell array, add suffix to every string 的后续问题,这对我没有帮助,因为strcat('x',{'1','2','3'}) 有效,但strcat('x', num2cell(1:3)) 无效:

>> 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"]
}

另外,根据Matlab: How to convert cell array to string array?的Matlab函数string(a),还没有实现:

“‘字符串’函数还没有在 Octave 中实现。`

【问题讨论】:

    标签: string vector type-conversion octave


    【解决方案1】:

    你可以结合cellstrint2str

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

    你也可以组合sprintfostrsplit

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

    您也可以使用num2str 代替int2str

    【讨论】:

    • 前两个在 x >> strcat('x', cellstr(int2str((1:3).'))) ans = { [1,1] = x [square] }>> cellstr(strcat('x', int2str((1:3).'))) ans = { [1,1] = x [square] } 之后给了我特殊的符号(看起来像一个 [正方形])。 ostrsplit 解决方案有效,但我想知道使用 strcat 的解决方案,因此问题没有解决:如何从“a”获取>> {'1','2','3'} ans = { [1,1] = 1 [1,2] = 2 [1,3] = 3 }。因此问题'如何将向量“a”转换为字符串的单元向量'。
    • 不,同样的事情,只是一个[1,1] = [square] 符号作为输出
    • @questionto42 他们为我工作。 a = 1:3;cellstr(int2str(a(:))) 可以在您的系统上运行吗?
    • 试试a = 1:3;cellstr(num2str(a(:)))
    • @questionto42 num2str 也加了!
    【解决方案2】:

    只是为了添加其他“明显”的解决方案

    arrayfun( @(x) strcat('x', num2str(x)), a, 'UniformOutput', false )
    

    或等效

    arrayfun( @(x) sprintf('x%d', x), a, 'UniformOutput', false )
    

    【讨论】:

      猜你喜欢
      • 2015-03-15
      • 2011-01-06
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多