I have a text file like this:

1st col  2nd col 

    20   8
    300  9
    31   5
    20   7
    20   7
    300  8

There is a long list of such numbers in a text file. I have to do two things with this file:

All those numbers in first column which are occuring less than ten times. Those all rows should be removed from the text file.

In the end, I should get a file with those entries omitted.

How can I achieve the above goal in Matlab or which function can help me in this regard?

This code , I tried:

data = importdata('check.txt'); 
data(data(:,1)<3,:)=[];

datacell = cellstr(num2str(data));

fileID = fopen('newfile.txt','w');
for k = 1:size(datacell,1)
    fprintf(fileID,'%s\n',datacell{k,:});
end
fclose(fileID);

check.txt:

32 7
32 7
32 7
6 9
32 7
32 7
56 7
6 87

newfile.txt: (output file)

32   7
32   7
32   7
 6   9
32   7
32   7
56   7
 6  87
有帮助吗?

解决方案

One can use importdata -

data = importdata(filepath1) %%// filepath1 is the path to the text file

num_occ = 3; %%// Minimum limit to no. of occurances for data to be kept

unqvals = unique(data(:,1))
data = data(~ismember(data(:,1),unqvals(histc(data(:,1),unqvals)<num_occ)),:)

datacell = cellstr(num2str(data));

fileID = fopen(filepath1,'w');
for k = 1:size(datacell,1)
    fprintf(fileID,'%s\n',datacell{k,:});
end
fclose(fileID);

Please remember that it will over-write data into the input file, as asked in comments.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top