how to extract specific rows of a .txt file ?

조회 수: 14 (최근 30일)
Ivan Mich
Ivan Mich 2022년 12월 13일
댓글: Voss 2022년 12월 15일
I have a problem with a code. I have a file with several rows and columns. Some rows, especially the first six numbers of them, are repeated line by line.
I want a final output that includes only the rows of which the first 6 numbers are repeated.
for example I attach an example of the input and of the output of what I mean
could you please help me?

채택된 답변

Voss
Voss 2022년 12월 13일
M = readmatrix('input.txt');
M(:,end) = [];
[~,~,jj] = unique(M,'rows','stable');
M([false; diff(jj) == 0],:) = [];
writematrix(M,'output.txt','delimiter','\t');
% check the output file:
type output.txt
1 2 3 5 6 8 2 4 6 8 9 6 3 5 6 8 9 10 2 4 6 8 9 6 7 8 9 10 22 6 8 7 9 6 2 5
  댓글 수: 2
Ivan Mich
Ivan Mich 2022년 12월 14일
ok, thank you. I have one more question. How could I count the number of the unique lines/rows? I have tried commands accumarray, but command window shows me
Error using accumarray
Too many output arguments.
for example i want to have an output like:
1 2 3 5 6 3
2 4 6 8 9 1
3 5 6 8 9 2
2 4 6 8 9 1
7 8 9 10 22 1
8 7 9 6 2 4
the last column includes the number of the repetitions of each line.
could you please help me?
Voss
Voss 2022년 12월 15일
M = readmatrix('input.txt');
M(:,end) = [];
[~,~,jj] = unique(M,'rows','stable');
M([false; diff(jj) == 0],:) = [];
M(:,end+1) = diff(find(diff([0; jj; 0])));
writematrix(M,'output.txt','delimiter','\t');
% check the input and output files:
type input.txt
1 2 3 5 6 8 5 1 2 3 5 6 8 4 1 2 3 5 6 8 3 2 4 6 8 9 6 5 3 5 6 8 9 10 3 3 5 6 8 9 10 9 2 4 6 8 9 6 2 7 8 9 10 22 6 3 8 7 9 6 2 5 1 8 7 9 6 2 5 4 8 7 9 6 2 5 8 8 7 9 6 2 5 6
type output.txt
1 2 3 5 6 8 3 2 4 6 8 9 6 1 3 5 6 8 9 10 2 2 4 6 8 9 6 1 7 8 9 10 22 6 1 8 7 9 6 2 5 4

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by