Error on loop on multiple ASCII files

2 次查看(过去 30 天)
Hello,
I have 100s of ASCII files with the same name in subfolders, I want to import them and perform the same operations on all of them.
I have managed to import the files but I have a problem with the importdata function. I get different ASCII files as I want but when I import the data, I get the same data from the first file. Therefore, all the further operations are done on the first file.
files=dir('F:\Teamdrive\TEST\**\*.ascii');
numfiles=length(files);
mydata=cell(1,numfiles);
for k = 1:numfiles
mydata{k} = importdata(files(k).name);
A{k}=size(mydata{k});
SelData{k}=mydata{k}(mydata{k}(:,4)>1,:); % extract matrix with only events>1
Area{k}=SelData{k}(:,1);
Diameter{k}=SelData{k}(:,2);
Eccentricity{k}=SelData{k}(:,3);
Events{k}=SelData{k}(:,4);
Density{k}=SelData{k}(:,5);
Clusternumber{k}=size(SelData{k});
MeanArea{k}=mean(Area{k});
end
I am not an expert in MATLAB and I am pretty sure it is a small mistake and I really appreciate your help in this matter.

采纳的回答

Stephen23
Stephen23 2022-2-15
编辑:Stephen23 2022-2-15
You should specify the path when importing the file data, for example:
P = 'F:\Teamdrive\TEST';
S = dir(fullfile(P,'**','*.ascii'));
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
M = readmatrix(F);
X = M(:,4)>1;
M = M(X,:); % extract matrix with only events>1
S(k).EventData = array2table(M(:,1:5),'VariableNames',{'Area','Diameter','Eccentricity','Events','Density'});
S(k).ClusterNumber = size(M);
S(k).MeanArea = mean(M(:,1));
end

更多回答(1 个)

Yongjian Feng
Yongjian Feng 2022-2-15
File.name only gives you the name of the file, not the path. Try:
files=dir('F:\Teamdrive\TEST\**\*.ascii');
numfiles=length(files);
mydata=cell(1,numfiles);
for k = 1:numfiles
fname = fullfile(files(k).folder, files(k).name);
mydata{k} = importdata(fname);
A{k}=size(mydata{k});
SelData{k}=mydata{k}(mydata{k}(:,4)>1,:); % extract matrix with only events>1
Area{k}=SelData{k}(:,1);
Diameter{k}=SelData{k}(:,2);
Eccentricity{k}=SelData{k}(:,3);
Events{k}=SelData{k}(:,4);
Density{k}=SelData{k}(:,5);
Clusternumber{k}=size(SelData{k});
MeanArea{k}=mean(Area{k});
end

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by