2013-01-08 38 views
6

考慮以下幾點:寫入單元陣列轉換成文本文件

DateTime = {'2007-01-01 00:00';'2007-02-01 00:00';'2007-03-01 00:00'}; 
Headers = {'Datetime','Data'}; 
Dat = [100,200,300]; 

Data = [DateTime,num2cell(Dat')]; 
Final = [Headers;Data]; 

我怎麼會在「最終」將數據寫入到一個製表符分隔文本文件。當變量只由數字輸入組成時,我知道如何使用fopen,fprintf等,但我正在努力解決這個問題。我曾嘗試過:

fid = fopen('C:\Documents\test.txt','wt'); 
fprintf(fid,'%s\t%s\n',Final{:}); 
fclose(fid); 

但是,這不會生成與matlab生成的格式相同的文本文件。這個問題怎麼解決?

+0

+1爲您提供的易於使用的代碼 – Acorbe

回答

6

該解決方案提供了我認爲您需要的東西;一些言論,我希望對大家有用是上側

DateTime = {'2007-01-01 00:00';'2007-02-01 00:00';'2007-03-01 00:00'}; 
Headers = {'Datetime','Data'}; 
Dat = [100,200,300]; 


% // In the way you used fprintf it expects just strings ('%s\t%s\n'), 
% // therefore Data should be composed exclusively by them. 
% // Numbers are converted to strings by using num2str 
% // by using cellfun we iteratively convert every element of num2cell(Dat') 
% // in strings, obtaining a cell 
Data = [DateTime,cellfun(@num2str, num2cell(Dat'), 'UniformOutput' , false)]; 
Final = [Headers;Data]; 

fid = fopen('test.txt','wt'); 

% // this iterates fprintf on the cell rows, giving you the output 
cellfun(@(x,y) fprintf(fid,'%s\t%s\n',x,y),Final(:,1),Final(:,2));  
fclose(fid); 

結果

Datetime Data 
2007-01-01 00:00 100 
2007-02-01 00:00 200 
2007-03-01 00:00 300 

編輯:(從評論)在N-立柱電池一般情況下,你可以簡單地去一個for循環,例如

for i = 1 : size(Final,1) 
    fprintf(fid,'%s ', Final{i,:}); 
    fprintf(fid,'\n'); 
end 

(結果相同,但不依賴於列數)。

+0

好的答案,但如果單元格數組超過2列(例如, 10列,包括寫入Final(:,1),Final(:,2),Final(:,3)等等。必須有一種方法可以在沒有指定單獨列的情況下工作? – KatyB

+0

@凱特,當然。事實上,cellfun所做的只是包裝一個for循環,在這種情況下是爲了行。你可以做的是寫你自己的循環涉及列也。我正在改變一般情況下的答案。 – Acorbe

+0

@Kate,請看看。 – Acorbe