MATLAB: How to extract values from rows and convert into a single column for several files

concatenateextract valuestranspose

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

Best Answer

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