前两天写了一个有限元的程序,有关数据的保存有点困惑,就是数据写入文本文件的时候只能是数据而不能连带文本(尤其是中文)一起写进去,这样程序的运行结果可读性就降低了,偶尔发现了这个程序,可以把cell数组完整写入txt里,中文也一样可以.然后我稍微修改了一下,使得数据与文本之间的对应保持上下一致.
分享一下,感觉里面有些语句也是值得借鉴的.hoho:
CODE
function cell2csv(datName,cellArray,trennZeichen)
% Writes cell array content into a *.csv file.
%
% CELL2CSV(datName,cellArray,trennZeichen)
%
% datName = Name of the file to save. [ i.e. 'text.csv' ]
% cellarray = Name of the Cell Array where the data is in
% trennZeichen = the number of blankspaces,and it has to be either
% great than zero or a positive interger.
% by Sylvain Fiedler, KA, 2004
% modified by bainhome,XJ,2006
if trennZeichen<=0|round(trennZeichen)~=trennZeichen
errordlg('trennZeichen has to be either great than zero or a positive interger.',...
'输入错误对话框')
return
else
str=' ';
for i=1:trennZeichen-1
str=[str,' '];
end
datei = fopen(datName,'w');
for z=1:size(cellArray,1)
for s=1:size(cellArray,2)
var = eval(['cellArray{z,s}']);
if size(var,1) == 0
var = '';
end
if isnumeric(var) == 1
var = num2str(var);
end
fprintf(datei,var);
if s ~= size(cellArray,2)
fprintf(datei,str);
end
end
fprintf(datei,'\n');
end
fclose(datei);
end
[转贴]:mathswork一个把cell数组(有中文)写入文本的程序
前两天写了一个有限元的程序,有关数据的保存有点困惑,就是数据写入文本文件的时候只能是数据而不能连带文本(尤其是中文)一起写进去,这样程序的运行结果可读性就降低了,偶尔发现了这个程序,可以把cell数组完整写入txt里,中文也一样可以.然后我稍微修改了一下,使得数据与文本之间的对应保持上下一致.
分享一下,感觉里面有些语句也是值得借鉴的.hoho:
CODE:[Copy to clipboard]function cell2csv(datName,cellArray,trennZeichen)
% Writes cell array content into a *.csv file.
%
% CELL2CSV(datName,cellArray,trennZeichen)
%
% datName = Name of the file to save. [ i.e. 'text.csv' ]
% cellarray = Name of the Cell Array where the data is in
% trennZeichen = the number of blankspaces,and it has to be either
% great than zero or a positive interger.
% by Sylvain Fiedler, KA, 2004
% modified by bainhome,XJ,2006
if trennZeichen<=0|round(trennZeichen)~=trennZeichen
errordlg('trennZeichen has to be either great than zero or a positive interger.',...
'输入错误对话框')
return
else
str=' ';
for i=1:trennZeichen-1
str=[str,' '];
end
datei = fopen(datName,'w');
for z=1:size(cellArray,1)
for s=1:size(cellArray,2)
var = eval(['cellArray{z,s}']);
if size(var,1) == 0
var = '';
end
if isnumeric(var) == 1
var = num2str(var);
end
fprintf(datei,var);
if s ~= size(cellArray,2)
fprintf(datei,str);
end
end
fprintf(datei,'\n');
end
fclose(datei);
end
==========================================================================
以下是我随手写的一个写入txt文本的程序.
CODE:
function read_csv_plus_text(t)
% 使用cell2csv读取文件的示例程序
clc
c=cell(4);
str=' ';
for i=1:t+2
str=[str,' '];
end
for i=2:4
for j=1:4
c{i,j}=rand(1);
c{1,j}=['测试',num2str(j),str];
end
end
cell2csv('ttt.txt',c,t)
下面这个是效果:
[
Last edited by hardstones on 2007-1-19 at 21:37 ]