How to find selection frequency in a txt file?
2 views (last 30 days)
Show older comments
Hello all, I have 10 txt files (I share an example) and each file has a list of selected items. I have 13 items in total. What I want to know is how many times each item was selected but I am getting an error (Input must be a MAT-file or an ASCII file containing numeric data with same number of columns in each row) message. I think the problem is the varying length of each line. How can I fix it? Thanks for the help.
txtFiles = dir('*.txt');
nFiles = length(txtFiles);
for i = 1:nFiles
txtCnt = load(txtFiles(i).name);
fprintf('-----%s-----\n',txtFiles(i).name);
Frq = zeros(1,13);
for Indx = 1:13
Frq(Indx) = sum(txtCnt == Indx);
end
Results = [1:13; Frq]
idx = find(Frq > mean(Frq))
end
0 Comments
Accepted Answer
Cris LaPierre
on 1 May 2023
Do not use load. I would probably use readmatrix. Note that your rows do not all have the same number of elements. These rows are padded with NaN.
data = readmatrix("Testing.txt")
7 Comments
Cris LaPierre
on 2 May 2023
Looks like MATLAB is trying to guess where the data starts. This is a result of having a different number of values in each row. Use the 'NumHeaderLines' name value pair to indicate that the data starts on the first line.
txtFiles = dir('*.txt');
nFiles = length(txtFiles);
for i = 1:nFiles
txtCnt = readmatrix(txtFiles(i).name,'NumHeaderLines',0)
fprintf('-----%s-----\n',txtFiles(i).name);
Frq = zeros(1,13);
for Indx = 1:13
Frq(Indx) = sum(txtCnt == Indx,'all');
end
Results = [1:13; Frq]
idx = find(Frq > mean(Frq))
end
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!