how to extract specific rows of a .txt file ?

7 vues (au cours des 30 derniers jours)
Ivan Mich
Ivan Mich le 13 Déc 2022
Commenté : Voss le 15 Déc 2022
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?

Réponse acceptée

Voss
Voss le 13 Déc 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 commentaires
Ivan Mich
Ivan Mich le 14 Déc 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 le 15 Déc 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by