aryan
aryan

Reputation: 23

How to use file name to sort and count files stored in a .mat file?

dbhole.mat file contains files name like: d1h1,d1h2,d1h3,d1h4,d2h1,d2h2,d3h1,d3h2,d3h4,d3h5,d3h6.

I want to count the number of files having a name that starts with d1 then d2 ,d3 and so on in a loop.

Upvotes: 0

Views: 157

Answers (1)

Suever
Suever

Reputation: 65460

If you mean that you want to get a list of the variables in a *.mat file that start with d1, d2, etc. You could use who and matfile to get a list of all variables. who accepts a regular expression which you can create specific to the variables you want to see.

matobj = matfile('filename.mat');

d1vars = who(matobj, '-regexp', '^d1h');
nD1 = numel(d1vars);

Or more generally in a loop

for k = 1:3
    vars{k} = who(matobj, '-regexp', ['^d', num2str(k), 'h']);

    % And get the number
    nVars(k) = numel(vars{k});
end

If you have an older version of MATLAB, you can load the file into a struct and then check the fields of that struct for the pattern that you'd like.

data = load('filename.mat');
variables = fieldnames(data);

isd1 = variables(~cellfun(@isempty, regexp(variables, '^d1h')));
nD1 = numel(isd1);

Upvotes: 1

Related Questions