for loop and "importdata" function

2 次查看(过去 30 天)
Hi. I hope some of you have time to help me with this one: I am trying to import some ascii-files with a 5 line header plus tab-separated numbers. I want to sum the tab-separated numbers only, and I have 200 files. The code I have written is:
clear;
files = dir('H:\testmappe_sletmig');
for i=1:length(files)
data = importdata(files(i).name, '\t', 6);
summarise = sum(data(:));
end
xlswrite(summarise_fetch,summarise);
However, I get an error message saying
"Error using importdata (line 215)
Unable to load file.
Use TEXTSCAN or FREAD for more complex formats.
Error in extractsum (line 8)
data = importdata(files(i).name, '\t', 6);
Caused by:
Error using fileread (line 27)
Could not open file .. Invalid argument."
Any help is much appreciated!
  4 个评论
per isakson
per isakson 2012-8-9
Can you import the files interactively with the Import Wizard? The [Import Data] button in the Workspace toolbar.
A Westergaard
A Westergaard 2012-8-9
编辑:A Westergaard 2012-8-9
Hi. Yes, I can import them manually by choosing "Import Data", either from Matlabs browser (right-click file -> Import Data) or with the Import Data button in the Workspace toolbar. The wizard automatically detects the header (5 lines) and the tab-separated data. The result is a textdata-matrix (with header info) and a data-matrix (with the actual data). Thanks

请先登录,再进行评论。

采纳的回答

A Westergaard
A Westergaard 2012-8-9
Ah, here we go. Problem solved!
clear;
files = dir('H:\testmappe_sletmig\*.txt');
for i=1:length(files)
eval(['x = importdata(files(i).name)']);
summarise(i) = sum(x.data(:));
end
xlswrite('summarise_fetch',summarise);

更多回答(1 个)

A Westergaard
A Westergaard 2012-8-9
Thank you for your inputs. I managed to get it working, however one challenge remains: I would like to export the sum of the data matrices to excel, so the sum of each input file is stored in a corresponding cell in an excel-sheet. When I use the code below, the sum of all the input files are stored in a single cell.
clear;
files = dir('H:\testmappe_sletmig\*.txt');
for i=1:length(files)
eval(['x=importdata(files(i).name)']);
summarise = sum(x.data(:));
end
xlswrite('summarise_fetch',summarise);

类别

Help CenterFile Exchange 中查找有关 Workspace Variables and MAT Files 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by