如何解决Octave:如何将整数向量转换为字符串元胞数组?
八度:
给定一个向量
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','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 中尚未实现“字符串”功能。`
解决方法
您可以结合使用 cellstr
和 int2str
:
strcat('x',cellstr(int2str((1:3).')))
or
cellstr(strcat('x',int2str((1:3).')))
您还可以结合使用 sprintf
和 ostrsplit
:
ostrsplit(sprintf('x%d ',1:3),' ',true)
or
strcat('x',ostrsplit(sprintf('%d ',true))
您也可以使用 num2str
代替 int2str
。
只是为了添加另一个“明显”的解决方案
arrayfun( @(x) strcat('x',num2str(x)),a,'UniformOutput',false )
或等效
arrayfun( @(x) sprintf('x%d',x),false )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。