how to extract specific rows of a .txt file ?

7 views (last 30 days)
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?

Accepted Answer

Voss
Voss on 13 Dec 2022
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 Comments
Ivan Mich
Ivan Mich on 14 Dec 2022
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 on 15 Dec 2022
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

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!