在MATLAB中将char中的字符串转换为数组

时间:2013-07-11 10:54:57

标签: arrays string matlab char

我在char数组中有一个字符串列表:

'gvs(0.000000000000000e+000, 1.601985139535780e+002)'
'gvs(-5.000000000000000e-005, 1.365231866954370e+002)'
'gvs(-1.000000000000000e-004, 1.169431404340180e+002)'
'gvs(-5.000000000000000e-004, 3.187711314514890e+001)'
'gvs(-2.000000000000000e-004, 8.589930648472340e+001)'

我试图将其转换为仅包含数字的数组(忽略gvs,逗号和括号),但我无法弄清楚我做错了什么?

cols = length(Variables) + length(Parameters);
% currently unused
rows = length(Results);

for a = 1:rows;
    Res(a,:) = sscanf ((Results{a,1}(1,:)),'%*s %f %f');
end

我也尝试过文本扫描,但我无法正常工作

for a = 1:rows;
    Res = cell (textscan ((Results{a,1}(1,:)),'%*s %f %f','Delimiter', {'(',' '},'MultipleDelimsAsOne',1));
end

非常感谢任何帮助!

谢谢

3 个答案:

答案 0 :(得分:2)

假设你有一个 char 数组(不是一个celltring):

s = ['gvs( 0.000000000000000e+000, 1.601985139535780e+002)'
     'gvs(-5.000000000000000e-005, 1.365231866954370e+002)'
     'gvs(-1.000000000000000e-004, 1.169431404340180e+002)'
     'gvs(-5.000000000000000e-004, 3.187711314514890e+001)'
     'gvs(-2.000000000000000e-004, 8.589930648472340e+001)']

然后你可以简单地textscan()

data = textscan(s','gvs(%f%f)','CollectOutput',1,'Delimiter',',');
data = data{1}
data =
         0  160.1985
   -0.0001  136.5232
   -0.0001  116.9431
   -0.0005   31.8771
   -0.0002   85.8993

如果s cellstring ,那么在调用textscan之前,请转换为char()

s = char(s);

答案 1 :(得分:2)

替换

Res(a,:) = sscanf ((Results{a,1}(1,:)),'%*s %f %f');

Res(a,:) = sscanf ((Results{a,1}(1,:)),'gvs(%f, %f)');

答案 2 :(得分:0)

考虑到你的字符串几乎是MATLAB数组兼容的格式,你可以犯罪并使用evalc

>> s = {
    'gvs( 0.000000000000000e+000, 1.601985139535780e+002)'
    'gvs(-5.000000000000000e-005, 1.365231866954370e+002)'
    'gvs(-1.000000000000000e-004, 1.169431404340180e+002)'
    'gvs(-5.000000000000000e-004, 3.187711314514890e+001)'
    'gvs(-2.000000000000000e-004, 8.589930648472340e+001)'};

>> C = evalc(['[' regexprep([s{:}], {'gvs\(' '\)'}, {'' ';'}) ']'])

ans =
                         0    1.601985139535780e+002
   -5.000000000000000e-005    1.365231866954370e+002
   -1.000000000000000e-004    1.169431404340180e+002
   -5.000000000000000e-004    3.187711314514890e+001
   -2.000000000000000e-004    8.589930648472340e+001