indexing a loop to run through multiple files

54 Ansichten (letzte 30 Tage)
C.G.
C.G. am 7 Jul. 2021
Kommentiert: C.G. am 7 Jul. 2021
I have experimental data in multiple csv files.
Ive written the code I want and checked this works by only inputting 1 specific file, but now I am trying to write in a loop to do the same for all the files. I am struggling with the indexing to get this to work, could anybody help?
%% input csv files
file = dir('*.csv'); %read the files into matlab
num_files = length(file); %record how many files have been found
[~, index] = natsort({file.name}); %sort the files into order
filelist = file(index);
%% Calculate granular temperature
for a = 1:length(num_files)
%read the table into matlab
table = table2array(readtable(filelist(a).name));
%save the particle ID's and velocity components
T = table(:, [1:4]);
%calculate resultant velocity for each particle (sqrt of the velcoities squared)
ResV = sqrt((T(:,2).^2) + (T(:,3).^2) + (T(:,4).^2));
%calculate mean resultant velocity of all the particles
ResVav = mean(ResV)
%calculate the average granular temperature
GTav = mean(ResV-ResVav)
end

Akzeptierte Antwort

Yongjian Feng
Yongjian Feng am 7 Jul. 2021
Try this:
%% input csv files
file = dir('*.csv'); %read the files into matlab
num_files = length(file); %record how many files have been found
sorted = sort({file.name});
for a = 1:length(num_files)
%read the table into matlab
table = table2array(readtable(sorted{a}));
%save the particle ID's and velocity components
T = table(:, [1:4]);
%calculate resultant velocity for each particle (sqrt of the velcoities squared)
ResV = sqrt((T(:,2).^2) + (T(:,3).^2) + (T(:,4).^2));
%calculate mean resultant velocity of all the particles
ResVav = mean(ResV)
%calculate the average granular temperature
GTav = mean(ResV-ResVav)
end
  5 Kommentare
Yongjian Feng
Yongjian Feng am 7 Jul. 2021
Bearbeitet: Yongjian Feng am 7 Jul. 2021
Yes. Try this:
%% input csv files
file = dir('*.csv'); %read the files into matlab
num_files = length(file); %record how many files have been found
sorted = sort({file.name});
result = [];
for a = 1:num_files
%read the table into matlab
table = table2array(readtable(sorted{a}));
%save the particle ID's and velocity components
T = table(:, [1:4]);
%calculate resultant velocity for each particle (sqrt of the velcoities squared)
ResV = sqrt((T(:,2).^2) + (T(:,3).^2) + (T(:,4).^2));
%calculate mean resultant velocity of all the particles
ResVav = mean(ResV)
%calculate the average granular temperature
GTav = mean(ResV-ResVav);
result(end+1) = GTav;
end
result
C.G.
C.G. am 7 Jul. 2021
Thank you for your help!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Cell Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by