Error on loop on multiple ASCII files

1 view (last 30 days)
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.

Accepted Answer

Stephen23
Stephen23 on 15 Feb 2022
Edited: Stephen23 on 15 Feb 2022
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 Comment
Roxane
Roxane on 15 Feb 2022
great thank you and also for the help in the matrix writing.

Sign in to comment.

More Answers (1)

Yongjian Feng
Yongjian Feng on 15 Feb 2022
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

Categories

Find more on File Operations in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!