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.
댓글 수: 7
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!