how to create a function that takes a txt file with a lot of columns and saves a new file (while keeping the old one) with 3 specific columns from the original ..

2 vues (au cours des 30 derniers jours)
Hey guys!
I have a tooon of txt files that I'd like to get 3 columns from each txt file and save them in the same folder. (the old txt file has 2932 columns, I want to select 3 of those 2932 and save that into a new file -- format doesn't matter... txt and excel are both okay) is there a way to automate this to do this for all my txt files? I am still rather new to matlab..
thank you!

Réponse acceptée

Peter Jarosi
Peter Jarosi le 18 Juil 2019
Modifié(e) : Peter Jarosi le 18 Juil 2019
You should have been more specific, so I could have given more accurate answer. For instance, a list of your filenames, names of your three columns, structure of your data (maybe these are in csv or xlsx format). Anyway, I hope that the following will help you:
myThreeCols = {'colName1', 'colName2', 'colName3'};
listOfFiles = {'myFile1.csv', 'myFile2.csv', 'myFile3.csv', 'myFile4.csv'};
numOfFiles = size(listOfFiles, 2);
for i = 1 : numOfFiles
myTable = readtable(listOfFiles{1,i}, 'ReadVariableNames', true); % Reading your file
myTable = myTable(:, myThreeCols); % Select your three columns
newFile = strcat('new_', listOfFiles{1,i}); % Insert prefix 'new_' in filename
writetable(myTable, newFile, 'WriteVariableNames', true); % Writing your file
end
If you upload some of your files I could be more specific. Perhaps your filenames could be iterable, that makes life easier.
  8 commentaires
Yoanna Ivanova
Yoanna Ivanova le 25 Juil 2019
Thanks Peter! Yes, now it works okay -- I removed a couple of rows in the beginning. Thank you!!

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by