Using an IF-else statement based on whether the number of files in a directory are equal

4 views (last 30 days)
Hiya,
I am looking to create some code that will look through my file directory and calculate how many .ctr files are present in each subfolder. Then, if the number of .ctr files in each subfolder are equal, the code will run. If not however, then the code will read an error message. I feel like this should be an IF - else statement, but I am not sure. I have some working code that will caluclate the number of files in a directory. I do not know how to do the next step however.
animals = {'List animal filenames'};
for an = 1:length(animals)
prefix = animals{an};
cd(['FILEPATHWAY',prefix,'\ctr\'])
a = dir('*.ctr');
n = numel(a)
end
Thanks

Answers (1)

Ameer Hamza
Ameer Hamza on 22 Sep 2020
Something like this should work
animals = {'List animal filenames'};
n = zeros(size(animals))
for an = 1:numel(animals) % numel is safer than length
prefix = animals{an};
cd(['FILEPATHWAY',prefix,'\ctr\'])
a = dir('*.ctr');
n(i) = numel(a)
end
condition = all(n==n(1));
if condition
% if condition is true, then execute the code
end
  2 Comments
RufusS
RufusS on 23 Sep 2020
Hi, thanks for the response.
I have added this to my code and I get an error message on this line:
n(i) = numel(a)
reading: array indicies must be positive integers or logical values.
Does this mean that the condition is not being met and the code is not running? If I remove the '(i)' after the 'n' then the code runs even when the conditions are not met.
Also, is there a way to have it read a custom error message for the user?
Thanks
Ameer Hamza
Ameer Hamza on 23 Sep 2020
Edited: Ameer Hamza on 23 Sep 2020
Sorry! I meant to write
n(an) = numel(a)
I am so being used to using i as loop variable that I didn't paid attention.

Sign in to comment.

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!