Matlab中str2double逆操作命令及字符数组元胞数组生成方法咨询
解答:Matlab中生成字符元胞数组的数值转换方案
你提到的需求——将数值数组转换成每个元素对应单独字符串的字符元胞数组(Matlab R2017a之前常作为"字符串"使用),确实没有像num2str或str2double那样的直接单命令,但有几种完全不需要循环的简洁实现方式:
方法1:用strsplit + num2str(最简洁)
先通过num2str把数值数组转成空格分隔的单个字符串,再用strsplit按空格拆分,直接得到字符元胞数组:
>> desired = @(x) strsplit(num2str(x)); >> desired([1 2 30]) ans = 1×3 cell array '1' '2' '30'
这个方法兼容绝大多数Matlab版本,代码简短直观。
方法2:用arrayfun + num2str(更灵活)
如果需要对每个数值的字符串格式做自定义(比如保留小数位数、添加前缀等),arrayfun的方式更方便:
>> desired = @(x) arrayfun(@num2str, x, 'UniformOutput', false); >> desired([1 2 30]) ans = 1×3 cell array '1' '2' '30'
比如要生成保留两位小数的字符串元胞数组,只需修改num2str的格式参数:
>> desired_with_decimal = @(x) arrayfun(@(n) num2str(n, '%.2f'), x, 'UniformOutput', false); >> desired_with_decimal([1 2 30]) ans = 1×3 cell array '1.00' '2.00' '30.00'
版本兼容补充(R2016b及以后)
如果你的Matlab版本是R2016b或更新,可以直接生成字符串数组(Matlab的原生字符串类型),再按需转成元胞数组:
>> % 生成原生字符串数组 >> string([1 2 30]) ans = 1×3 string array "1" "2" "30" >> % 转成字符元胞数组 >> cellstr(string([1 2 30])) ans = 1×3 cell array '1' '2' '30'
内容的提问来源于stack exchange,提问作者Josiah Yoder




