字符串是元胞数组
嗯,不是真的.. 这是一个矩阵,但请继续阅读。
我猜元胞数组是 MATLAB 中最神秘的数据类型。所以让我们揭开神秘面纱 ;-)
假设
fruits = {...
'banana',...
'apple',...
'orange'...
}
首先,小数组不需要整数索引。最好使用类似 foreach 的结构。确实,
for index = 1:numel(fruits)
fruits{index}
end
等价于
for fruit = fruits
fruit
end
对吗?
嗯,不完全是。第一个循环产生字符串,而第二个循环产生单元格。你可以检查一下
for index = 1:numel(fruits)
[isstr(fruits{index}) iscell(fruits{index})]
end
for fruit = fruits
[isstr(fruit) iscell(fruit)]
end
,即[1 0]和[0 1]。
如果您发现了差异,那么您必须知道如何处理下一个示例(在这个示例中确实与您的问题有关 (!) 我保证!)。假设您尝试在循环中进行水平连接:
for fruit = fruits
[fruit 'is a fruit']
end
你会得到
ans =
'banana' 'is a fruit'
等等。为什么?显然,此代码尝试将嵌套单元格数组连接到字符串(包含字符矩阵的单元格数组,这些字符构成字符串,如“香蕉”)。所以,正确答案是
使用 {:}
for fruit = fruits
[fruit{:} 'is a fruit']
end
神奇的是,这已经产生了预期的'香蕉是水果','苹果是水果',等等。
提示
一些提示:
- 无索引循环与
for fruit = [fieldnames][1](fruits)' 中的结构很好地配合使用
- 以上是 true 对于开源 octave
- 香蕉不仅仅是水果,在分类学上它也是一种草本植物 ;-) 就像 MATLAB 中的 'banana' 既是字符串又是矩阵,即 assert(isstr('banana') && ismat('banana'))通过,但 assert(iscell('banana')) 失败。
-
{:} 等价于 cell2mat
PS
您的问题的解决方案可能如下所示:
给定
vcell = {...
'v' 576.5818 3.0286 576.9270;
'v' 576.5818 3.0286 576.9270
}
将仅按索引的数字类型转换为字符串
vcell(cellfun(@isnumeric, vcell)) = cellfun(@(x) sprintf('%.5f', x), vcell(cellfun(@isnumeric, vcell)), 'UniformOutput', false)
以上代码输出
vcell =
'v' '576.58180' '3.02860' '576.92700'
'v' '576.58180' '3.02860' '576.92700'
可以串联。