在 Matlab 中使用 textscan 的浮点精度错误

Wrong float precision using textscan in Matlab

我在 matlab 中设计了一个函数,它允许我(或者我认为)从看起来像这样的文本文件中提取数据(至少是开头)

G1 50
G2 50
M-0.35 0
M-0.05 0.013
M3.3 0.1
M9.75 0.236
M17.15 0.425
M25.85 0.666
M35.35 0.958

我的想法是将我拥有的字母及其位置与向量相匹配(因为只有 M 旁边的值对我来说真的很有趣),然后将另外两个数字放入向量中。 处理结束效果很好,但我在代码结束时得到的值有时与真实值相差甚远。

例如,我得到的不是 [0 0.013 0.1 0.236 0.425 0.666 0.958],而是 [0 0.013 0.1010 0.237 0.426 0.666 0.959]。 这不是这样的问题,第一列的问题更严重:它没有达到 90,而不是最大值 119。我有一个代码可以正确处理整数,但现在我使用浮点数失败了每次。

我将尝试只显示代码中有趣的部分:

nom_essai='test.txt'     
fid1 = fopen(nom_essai, 'rt');
tableau = textscan(fid1, '%s %.5f ', 'HeaderLines', 1, 'CollectOutput', true); %There are a few lines that I skip because they give the parameters, I get them with another line of the code
colonne_force=tableau{1}; %on recupere la premiere colonne
colonne_deplacement=tableau{2}; %on recupere la seconde colonne


indice=2*found_G+found_F+3*found_R; %this is the result of the treatment on colonne_force to match an index with the letter, which helps me keep the period next to G and the 2 values next to M.

force=linspace(0,0,length(n_indices)); %initialisation
    deplacement=linspace(0,0,length(n_indices)); %initialisation
    temps=linspace(0,0,length(n_indices)); %initialisation


    for k=1:length(colonne_force) %%%%k is for the length of my vectors, while j is for the length of the columns
        if indice(k)==2 %un G est trouve => temps d'echantillonnage
            T=colonne_deplacement(k); %to keep the period next to G
            end
        elseif indice(k)==1 %an F is found : skip it
        elseif indice(k)==3 %an R is found : skip it
        else %an M is found : I need to get the values on these lines
            j=j+1;
            deplacement(j)=colonne_deplacement(k); %I keep the value on the second column
            M=strsplit(colonne_force{k},'M'); %I get the string 'MXXX'
            force(j)=str2double(M{2}); %I recover this string without the M, and convert the number to double                 
        end
    end

我想要的精度是保持像 [M108.55 23.759] 这样的值最多 3 位数。

在此先感谢您,如果我未能仅提供包含问题的代码部分,请随时询问任何信息。

将您的代码稍微修改为:

nom_essai='test.txt';     
fid1 = fopen(nom_essai, 'rt');
tableau = textscan(fid1, '%s %f ', 'HeaderLines', 1, 'CollectOutput', true); % Change to %f not to miss significative figures
colonne_force = tableau{1}; %on recupere la premiere colonne
colonne_deplacement=tableau{2}; %on recupere la seconde colonne

% Check if has M

hasM = cellfun(@(x) any(x == 'M'), colonne_force);

column2 = colonne_deplacement(hasM);

column1 = colonne_force(hasM);
column1 = cellfun(@(x) str2double(x(2:end)), column1); % delete M and convert to double

保留精度: