How to extract values from rows and convert into a single column for several files
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Jan
2018-5-23
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.
采纳的回答
Ameer Hamza
2018-5-23
编辑:Ameer Hamza
2018-5-23
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.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!