2017-05-22 72 views
1

在txt文件印刷我有一個輸入.txt文件這樣「NULL」而不是0利用Matlab

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 

everithing工作正常,exept事實次而不是0代碼打印空字符。有什麼建議麼?

+0

輸入文件中的符號a,b,c等代表什麼?我想你實際上是在減去數字?你能發佈一個輸入文件的工作示例嗎? – Dennis

+0

是的。我編輯了問題 – drSlump

回答

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 
1

除了使用%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); 
+0

謝謝。這使我的代碼更加精簡 – drSlump