2014-02-21 53 views
2

我想使用fprintf寫入數據文件。說我有包含這樣的數據的矩陣:fprintf打印字符和數字沒有循環

Values = [ 1, 735123.0, 23, 24, 25; 
      2, 735123.5, 34, 35, 36; 
      ... 
      8000, 739122.5, 21, 22, 43] 

我可以用寫一個文件:

fprintf(FileID, '%d, %f, %d, %d, %d', Values') 

但實際上該第二列表示時間(datestr(735123.5)= 11-Sep- 2012 12:00:00)我想fprintf中打印日期在數據文件中的第二列,因此該文件將讀取

1, 11-Sep-2012 00:00:00, 23, 24, 25 
2, 11-Sep-2012 12:00:00, 34, 35, 36 
... 
8000, 24-Aug-2023 12:00:00, 21, 22, 43 

我矩陣是成千上萬行的長,所以我更喜歡不必循環 逐行。

任何建議如何進行?

回答

0

喜歡的東西

n = num2cell(Values'); 
n(2,:) = cellfun(@datestr, n(2, :),'UniformOutput', false); 
fprintf(FileID, '%d, %s, %d, %d, %d', n{:}); 

雖然cellfun基本上是一個循環。

+0

完美,謝謝。我正在嘗試mat2cell,並沒有工作。 cellfun似乎比我的循環更快。或者也許是'UniformOutput'部分。 – EddyTheB

+1

此外,爲了將來的參考,我已經使用'@(x)datestr(x,'dd-mm-yyyy HH:MM:SS')'而不是'@datestr'來確保午夜時間的輸出。 – EddyTheB

0

沒有for循環或cellfun

separator = repmat(', ',size(Values,1),1); %// column used as separator 
lineFeeds = repmat('\n',size(Values,1),1); %// column of line feeds 
string = [ num2str((Values(:,1))) ... 
      separator ... 
      datestr(Values(:,2)) ... 
      separator ... 
      num2str(Values(:,3)) ... 
      separator ... 
      num2str(Values(:,4)) ... 
      separator ... 
      num2str(Values(:,5)) ... 
      lineFeeds ]; 
string = reshape(string.',1,[]); %'// put everything in one row 
FileID = fopen('tmp.txt', 'wt'); %// use 't', or '\n' may not get written to file 
fprintf(FileID, string); 
fclose(FileID);