写数据到excel文件,MATLAB

我在Windows 7机器上使用MatlabR2011a 。 我有一个635文本文件的文件夹。 每个文件包含多行和2列。 我正在试图循环浏览文件夹并读取每个文件,并将这些值写入excel。 到目前为止,这是我的:

close all; clc; dirname = uigetdir; Files = dir(fullfile(dirname,'*.txt')) for k = 1:635 j =1 filename = fullfile(dirname,Files(k).name); fid = fopen(filename); x = fgetl(fid) while ischar(x) x = fgetl(fid) a2 = strtrim(x); a3 = textscan(a2,'%s'); a4 = a3{1}{1}; a5= a3{1}{2}; pos3 = strcat('A',num2str(j)); xlswrite('sample_output',{a4,a5},'Sheet1',pos3) j = j+1; end fclose(fid); end 

完成读取第一个文件后,它不断给我下面的错误。

  Error using ==> strtrim Input should be a string or a cell array of strings. 

示例input文件如下所示:

  15076 4636259 15707 4636299 15714 1781552 15721 4204950 15730 2174919 16209 4636510 16413 4758572 16470 4445808 17519 311397 17667 2116489 17739 1729694 18024 3210756 18627 3714194 18695 4192858 19141 632766 19318 1923574 19438 1255216 19493 4635020 19771 4770250 

我怎样才能解决这个问题? 将感谢帮助!

在while循环中,切割线

 x=fgetl(fid) 

…并在j = j + 1之后将其粘贴到结束语句之前。

发生这个错误是因为你在while语句之前得到一行,然后你使用while语句来testingstring的有效性(迄今为止都是好的),但是在你执行string操作之前立即得到下一行。 在while块的开始处对fgetl的调用可能会返回一个EOF,导致后续的string操作函数失败。

另外…如果你像这样设置for循环,代码将会更加健壮

 for k=1:numel(Files) 

由于你所有的数据都是数字,所以这个工作。 试一试。

 dirname = uigetdir; Files = dir(fullfile(dirname,'*.txt')) j =0; for k = 1:numel(Files) filename = fullfile(dirname,Files(k).name); x = dlmread(filename,'\t'); %# I assume tab-delimiter j = j + size(x, 1); xlswrite( 'sample_output', x, 'Sheet1',sprintf('A%d',j) ) end