How to extract values from rows and convert into a single column for several files
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Isma_gp
am 23 Mai 2018
Kommentiert: Ameer Hamza
am 23 Mai 2018
Hi, I have several NUM_*.dat files as the two attached. I need to extract rows (excluding some specific values) from that file and convert them into a combined column of values. For instance, from the first file, I need to get a single column which in order includes the values from the file starting in row 2, but excluding the first value of the even rows (row2,4,6...). This process should be done for several NUM_*.dat files, so that the final result is a file which contains as many columns as NUM_*.dat files. Can I get some help to do this in an efficient way? Thanks
2 Kommentare
Jan
am 23 Mai 2018
What have you tried so far? Which specific problem do you have? It would be inefficient, if the readers guess, if creating a loop to adjust the file names belongs to the problem or not. So please post the existing code.
Akzeptierte Antwort
Ameer Hamza
am 23 Mai 2018
Bearbeitet: Ameer Hamza
am 23 Mai 2018
The following code will work. It will read every odd line, remove the first number and add it to a column. Since we don't know in advance how many values will be in each file, therefore I used a cell array. If you know the number of elements in each file in advance, consider preallocating the memory
files = dir('NUM*.txt');
matrix = cell(1, numel(files));
for i=1:numel(files)
f = fopen(files(i).name);
while true
line = fgetl(f); % to ignore the odd lines
line = fgetl(f);
if line == -1
break
end
line_ = textscan(line, '%f');
matrix{i} = [matrix{i}; line_{:}(2:end)];
line = fgetl(f); % to ignore every third empty line
end
fclose(f);
end
You can access the values like this: matrix{1} will give you column for the first file, matrix{2} for the second file and so on.
7 Kommentare
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!