A script to append a column with values and read multiple txt files from different folders

1 view (last 30 days)
I have 6 folders, in each folder there is a text file with three columns omega, G' and G" with values. Want to add a new column viscosity with values and also read all the text files in just one code from different folders
a=readtable('Pure_melt.txt');
a1=a(:,1);
a1=table2array(a1);
b=a(:,2);
b=table2array(b);
g1=b.^2;
c=a(:,3);
c=table2array(c);
g2=c.^2;
v=sqrt(g1+g2)./a1;
f=[a1'; b'; c'; v'];
file_ID=fopen('Pure_melt.txt','w');
t=' omega gp gdp vis';
fprintf(file_ID,sprintf('%s %s %s %s\n',t));
fprintf(file_ID,'\n %3f %3f %3f %3f \n',f);
fclose(file_ID);
This is just one code where i run the code for just one text file
want to run all the 6 text file in just one code
Thanks in advance

Answers (1)

Kautuk Raj
Kautuk Raj on 14 Jun 2023
This is an example MATLAB code that should accomplish what you described:
% Define the names of the folders containing the text files
folder_names = {'folder1', 'folder2', 'folder3', 'folder4', 'folder5', 'folder6'};
% Initialize empty arrays to store the data
omega_all = [];
Gprime_all = [];
Gdoubleprime_all = [];
viscosity_all = [];
% Loop over the folders
for i = 1:length(folder_names)
% Get the name of the folder
folder_name = folder_names{i};
% Get the names of all the text files in the folder
file_names = dir(fullfile(folder_name, '*.txt'));
% Loop over the text files
for j = 1:length(file_names)
% Get the name of the text file
file_name = fullfile(folder_name, file_names(j).name);
% Load the data from the text file
data = load(file_name);
% Extract the columns of interest
omega = data(:, 1);
Gprime = data(:, 2);
Gdoubleprime = data(:, 3);
% Calculate the viscosity
viscosity = Gdoubleprime ./ omega;
% Append the data to the arrays
omega_all = [omega_all; omega];
Gprime_all = [Gprime_all; Gprime];
Gdoubleprime_all = [Gdoubleprime_all; Gdoubleprime];
viscosity_all = [viscosity_all; viscosity];
end
end
% Combine the data into a single matrix
data_all = [omega_all, Gprime_all, Gdoubleprime_all, viscosity_all];
% Save the data to a file
save('all_data.mat', 'data_all');
This code assumes that the text files have the same format in all folders, with three columns of data separated by whitespace. If the format is different, you may need to modify the code to read the data correctly.
The code loads the data from each text file, calculates the viscosity, and appends the data to arrays. Then it combines the arrays into a single matrix and saves the matrix to a file.

Community Treasure Hunt

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

Start Hunting!