Count number of unique .mat files in a folder
Show older comments
Hello,
I have a set of folders and subfolder which I wish to analyze. I used the following code to determine the .mat files Info and names in a specific subfolder:
function [dirinfo, folders, matFilesInfo, matFilesNames] = getFolderNames( rootPath )
dirinfo = dir(rootPath);
dirinfo(~[dirinfo.isdir]) = []; %remove non-directories
tf = ismember( {dirinfo.name}, {'.', '..'});
dirinfo(tf) = []; %remove current and parent directory.
if ~isempty(dirinfo)
folders = extractfield(dirinfo,'name');
else
folders = [];
end
matFilesInfo = dir(fullfile(rootPath, '*.mat'));
if ~isempty(matFilesInfo)
matFilesNames = extractfield(matFilesInfo,'name');
else
matFilesNames = [];
end
end
For example I have the following values in matFilesNames:
6×1 cell array
{'RX_Phase_SA_RXG0_TXG20_1.mat'}
{'RX_Phase_SA_RXG0_TXG20_2.mat'}
{'RX_Phase_SA_RXG0_TXG20_3.mat'}
{'RX_Phase_SA_RXG0_TXG30_1.mat'}
{'RX_Phase_SA_RXG0_TXG30_2.mat'}
{'RX_Phase_SA_RXG0_TXG40_1.mat'}
I would like to have unique values with the count for each unique case.
For the above example:
3 files for 'RX_Phase_SA_RXG0_TXG20', 2 files for 'RX_Phase_SA_RXG0_TXG30' and 1 file for 'RX_Phase_SA_RXG0_TXG40'
How can I do this w/o huge number of loops and string splits?
Thank you!
1 Comment
Stephen23
on 22 Dec 2021
Try this
S = dir(fullfile(rootPath,'**','*.mat'))
Accepted Answer
More Answers (1)
The simple MATLAB approach is to use one of the histogram functions rather than a loop, e.g.:
% S = dir(fullfile(rootPath,'**','*.mat'));
% C = {S.name};
C = { ...
'RX_Phase_SA_RXG0_TXG20_1.mat'; ...
'RX_Phase_SA_RXG0_TXG20_2.mat'; ...
'RX_Phase_SA_RXG0_TXG20_3.mat'; ...
'RX_Phase_SA_RXG0_TXG30_1.mat'; ...
'RX_Phase_SA_RXG0_TXG30_2.mat'; ...
'RX_Phase_SA_RXG0_TXG40_1.mat'};
[U,~,X] = unique(regexprep(C,'_[^_]+$',''))
N = histcounts(X)
optional output display:
compose("%s: %d",string(U),N(:))
Categories
Find more on Variables in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!