从矩阵中提取数据

时间:2016-08-18 13:01:51

标签: matlab matrix

我有这个原始(字符串)数据。我想首先将其更改为数字,然后通过删除斜杠将第三列拆分为两个,这样我的最终答案将是四(4)列矩阵。

[-0.095]    [ 3.251]    '0.152 / 0.0415' 
[   NaN]    [   NaN]    [            NaN]
[ 3.194]    [ 3.194]    [            NaN]
[ 3.251]    [ 9.911]    '0.152 / 0.0387' 
[   NaN]    [   NaN]    [            NaN]
[ 9.854]    [ 9.854]    [            NaN]
[ 9.911]    [16.571]    '0.152 / 0.0387' 
[   NaN]    [   NaN]    [            NaN]
[16.514]    [16.514]    [            NaN]
[16.571]    [23.211]    '0.129 / 0.0535' 
[23.154]    [23.154]    [            NaN]
[23.211]    [29.851]    '0.129 / 0.0535' 
[29.794]    [29.794]    [            NaN]

1 个答案:

答案 0 :(得分:0)

假设输入数据在Input.txt文件中 输出矩阵是A.
代码从文件到字符串读取行格式,并使用sscanf将字符串解析为向量 每个解析的矢量附加到矩阵A的底部 字符串没有除法时的特殊情况的代码测试(其中最后一个元素是NaN)。

检查以下内容:

f = fopen('Input.txt', 'r');

A = [];

while ~feof(f)
    s = fgets(f); %Read row from file.

    if isempty(strfind(s, '/'))
        Q = [sscanf(s, '[%f] [%f]'); NaN; NaN];    %First case: last element is NaN: [ 3.194]    [ 3.194]    [            NaN]
    else
        Q = sscanf(s, '[%f] [%f] ''%f / %f''');    %Second case: last element is x / y: [ 3.251]    [ 9.911]    '0.152 / 0.0387' 
    end

    %Concatenate vector Q to the bottom of A matrix;
    A = [A; Q'];    
end

fclose(f);