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 ビュー (過去 30 日間)
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!

採用された回答

Peter Jarosi
Peter Jarosi 2019 年 7 月 18 日
編集済み: Peter Jarosi 2019 年 7 月 18 日
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 件のコメント
Yoanna Ivanova
Yoanna Ivanova 2019 年 7 月 25 日
Thanks Peter! Yes, now it works okay -- I removed a couple of rows in the beginning. Thank you!!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by