我必须在Matlab中关注char:
charList = '{''68'', ''10''}'
(我实际上不是在Matlab中创建这个,这是来自.NET,但为了制作这个例子,我刚刚创建了它......)
现在我想这样做:
cellArray = str2double(charList)
结果是' NaN' ..因为这只是一个字符。是否可以仅从具有正确语法的char创建char数组?
e.g。像char2cellArray?
谢谢!
答案 0 :(得分:3)
另一种方法是使用textscan
并使用'Whitespace'
参数过滤掉不需要的字符。
例如:
charList = '{''68'', ''10'', ''1.234'', ''-15'', ''-1.234''}';
nums = textscan(charList, '%f', 'Whitespace', '{} \b\t''', 'Delimiter', ',', 'CollectOutput', true);
nums = [nums{:}]; % Denest the double array from the cell
这给了我们:
>> nums
nums =
68.0000
10.0000
1.2340
-15.0000
-1.2340
答案 1 :(得分:2)
最简单的解决方案是在该字符串上使用eval
,因为单元格数组是在字符串中编码的。但是我不推荐这种方法,因为eval
不仅不安全,而且在eval
中运行任何代码时都不会执行代码优化:
cellArray = str2double(eval(charList));
或者,您可以使用正则表达式提取出现的任何数字并将其转换为数组:
cellArray = str2double(regexp(charList, '-?\d+\.?\d*', 'match'));
正则表达式允许提取浮点数,而不仅仅是整数。此外,可以提取负值。