Concatenate data from processing of imported text files
Afficher commentaires plus anciens
I am extracting text files from a path on my computer, using a for loop to process each text file. This text file undergoes a simple processing like here I am extracting the first two columns of the text file and storing it in K9. Typically K9 has dimensions 14000*2 and varies slightly like 14002*2. How can I concatenate all K9 values in a new matrix say K10? My text files have names A1.txt, A2.txt, A3.txt,...and A22.txt. I also need a new row (first row) where names of these text files are stored so that I understand that the data belongs to this particular text file. I have searched the matlab forum for help in this regard, however could not solve the question. Here is my code
directory = 'D:\PhD\Matlab code';%path from where Iam extracting files
textfiles = fullfile(directory,'*.txt');
dinfo = dir(textfiles);
for K = 1:length(dinfo)
incidentfile = fullfile(directory, dinfo(K).name);
K0 = importdata(incidentfile);
K1 = K0.data;%I extract only the matrix data useful to me not the rest
K9= [K1(:,1) K1(:,2)];%extract the first two columns not the third
end
Please help. Thank you.
Regards
Réponse acceptée
Plus de réponses (1)
Jakob B. Nielsen
le 9 Déc 2019
You cant join two arrays of different size, but you can use a structure to store the data which will give you almost the same thing.
For example
directory = 'D:\PhD\Matlab code';%path from where Iam extracting files
textfiles = fullfile(directory,'*.txt');
dinfo = dir(textfiles);
for K = 1:length(dinfo)
incidentfile = fullfile(directory, dinfo(K).name);
K0 = importdata(incidentfile);
K1 = K0.data;%I extract only the matrix data useful to me not the rest
K9= [K1(:,1) K1(:,2)];%extract the first two columns not the third
concstruct(K).data=K9;
concstruct(K).name=dinfo(K).name;
end
If you absolutely must join the K9's in the same matrix, you will have to either cut all that exceeds 14000 rows, or alternatively add trailing zeros to any matrix up to the dimension of the larger matrix. You cant have numbers and characters in the same array, so consider array2table of your final array, and then have the variable names in the table be your file name references. But I would still just use the structure way, it gives you - essentially - the same :)
2 commentaires
Stephen23
le 9 Déc 2019
There is no need to create a new structure, you can just use the strucutre returned by dir:
dinfo(K).data = K9;
Venkatesh M Deshpande
le 10 Déc 2019
Modifié(e) : Venkatesh M Deshpande
le 10 Déc 2019
Catégories
En savoir plus sur Text Data Preparation dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!