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 ..

1 visualización (últimos 30 días)
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!

Respuesta aceptada

Peter Jarosi
Peter Jarosi el 18 de Jul. de 2019
Editada: Peter Jarosi el 18 de Jul. de 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 comentarios
Yoanna Ivanova
Yoanna Ivanova el 25 de Jul. de 2019
Thanks Peter! Yes, now it works okay -- I removed a couple of rows in the beginning. Thank you!!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Data Import and Analysis en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by