【问题标题】:'NULL' instead of 0 printed in txt file using Matlab使用 Matlab 在 txt 文件中打印 'NULL' 而不是 0
【发布时间】:2017-05-22 11:07:57
【问题描述】:

我有一个这样的输入 .txt 文件

head1      head2       head3      head3

0.004   5.104175   -1.651492   0.074480
0.015   5.104175   -1.327670   0.087433
0.025   5.104175   -1.181950   0.093910
...

并且我想将第一行减去同一个文件中的所有后续行,即打印一个这样的.txt文件:

0       0           0          0 
0.011   0   -0.323825   -0.012953
...

这是我的代码:

for i = 1:length(x) %read all the files contained in folder_inp

    %%check file extensions
    [pathstr,name,ext] = fileparts(x(i).name); 
    %%if it is a text file...
    if strcmp('.txt',ext)
        s = importdata(strcat(folder_inp,'\',x(i).name));
        init = s.data(1,:);
        for k=1:length(s.data)
            if s.data(k,:) == init
                s.data(k,:) = zeros(1,length(s.data(k,:)));
            else 
                s.data(k,:) = s.data(k,:)-init;
            end
        end

         fid = fopen( strcat(folder_out,'\',name,'.txt'), 'w' );
         formatSpecs = '%20s %20s %20s %20s \r';
        for j = 1:length(s.data)
            if j == 1
                fprintf(fid,formatSpecs,'head1','head2','head3','head4');
            elseif j==2 
                fprintf(fid,'\n') ;
            else 
                fprintf(fid,formatSpecs,s.data(j,1),s.data(j,2),s.data(j,3),s.data(j,4));
            end
        end

        fclose(fid);

     end

end

一切正常,除了代码打印空字符而不是 0 的事实。有什么建议吗?

【问题讨论】:

  • 输入文件中的符号a、b、c等代表什么?我想你实际上是在减去数字?你能发布一个输入文件的工作示例吗?
  • 是的,没错。我已经编辑了问题

标签: matlab file text


【解决方案1】:

您的问题是您在调用fprintf 时使用了错误的format specifiers。您正在使用转换字符%s,它将您的输入参数解释为字符串。由于您的数据实际上是数字,因此 MATLAB 会首先尝试将它们转换为字符串。对于浮点值,这似乎可以正常工作,但整数值被解释为 ASCII 代码并转换为它们等效的 ASCII 字符。注意这个例子,使用%s:

>> sprintf('%s ', [pi 0 65 66 67 pi])

ans =

3.141593e+00  ABC 3.141593e+00

pi 的值被转换为适当的字符串,但 0 65 66 67 被转换为 NULL 字符加上 ABC

您应该对数值使用格式说明符,例如%f

>> sprintf('%f ', [pi 0 65 66 67 pi])

ans =

3.141593 0.000000 65.000000 66.000000 67.000000 3.141593

【讨论】:

    【解决方案2】:

    除了使用%f 可以解决您的问题之外,您还可以执行以下操作来清理代码并使其适用于任意数量的列和任何标题文本。

    % getting the headers
    oldFile = fopen('text_in.txt');
    headers = fgets(oldFile);
    fclose(oldFile);
    
    % reading and manipulating the data
    data = dlmread('test.txt', '\t', 1, 0); % skip the first row of headers
    data = repmat(data(1,:), size(data, 1), 1) - data; % subtract first row
    
    % the format spec
    formatspec = [repmat('%f ',1 , size(data, 2)) '\r\n'];
    
    % writing to the new file
    fid = fopen('text_out.txt', 'w');
    fprintf(fid,'%s',headers); % the header
    fprintf(fid, formatspec, data'); % the data
    fclose(fid);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      相关资源
      最近更新 更多