How to count how many sub folders under a folder

In a folder, there are many sub folder, how do we count how many sub folder they are?

1 Comment

Note that KSSV's answer actually counts the total contents of a folder, including any files.
See also:
As Walter Roberson wrote in that last link: "In short: if your code assumes that '.' and '..' are the first two entries in a directory, your code has a bug (even in MS Windows). If your code assumes that directory entries are returned in any sorted order, your code has a bug (in all OS.)"

Sign in to comment.

Answers (2)

go the folder...and use
k = dir ;
N = length(k)-2 ;
N should be the number of sub folders.

7 Comments

In Matlab, my current directory is default, ...../bin,how do I go to the directory which I want to?
I mean use command to go to
Jason
Jason on 4 Mar 2016
Edited: Jason on 4 Mar 2016
N = length(k)-2 ; Why we should minutes 2, could you give me some reference? why field 1 and field is . and ..?
k = dir ;
k will be a structure. First two will give . and .. . So minus 2. There are other ways too .
You can go to your directory either by cd 'path' or using the browse folder icon .
Note that this answer actually counts the total contents of a folder, including any files.
Thank you. But his solution work pretty well for me. I just want to check how many items their, I do not care if it is directory or not.
This answer also includes any files. So I don't think it is the answer

Sign in to comment.

The correct answer would be something like this:
P = 'absolute or relative path to the folder';
S = dir(P);
N = nnz(~ismember({S.name},{'.','..'})&[S.isdir])

Categories

Asked:

on 4 Mar 2016

Edited:

on 24 Nov 2023

Community Treasure Hunt

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

Start Hunting!