MATLAB: How to create a new folder each time I run a code

for loopmatlab functionmkdirnew folder

I want to make a new folder each time I run my code.
Example:
If there is a folder named 'newFolder', then generate newFolder1 after running once.
If there is a folder named 'newFolder7', then generate newFolder8 after running once.
In general, if there is a folder named 'newFolderx', then generate newFolderx+1 after running once.
I am using this code below: (important part is the nextname fumction usage)
mkdir("C:/Users/vaidy/Desktop/JAY/Labwork/Models for devices/FeFETIMT model/MATLAB code/Voltage source/25x25/" + nextname('newFolder','1')).
mkdir("C:/Users/vaidy/Desktop/JAY/Labwork/Models for devices/FeFETIMT model/MATLAB code/Voltage source/25×25/" + nextname('newFolder','1')).
But this generates a new folder only for the first time, and later it says that the folder already exists.

Best Answer

There are two problems with your code:
  1. You are not passing nextname the path of that location, so instead of looking in the location that you want, it will only check the current directory. How do you expect nextname to know where to look for folders if you do not tell it where to look?
  2. The current version of nextname can optionally return exactly the same absolute/relative path of the input file/folder name (plus the incremented suffix) in its output, so you do not need to concatenate the path onto its output.
You need to use nextname something like this:
D = 'C:/Users/vaidy/Desktop/JAY/Labwork/Models for devices/FeFETIMT model/MATLAB code/Voltage source/25x25';
mkdir(nextname(fullfile(D,'newFolder'),'1','',true))
This worked when I tried it just now:
>> D = 'C:\Users\stephen.cobeldick\Documents'; % not the current folder!
>> dir(fullfile(D,'newF*'))
'C:\Users\stephen.cobeldick\Documents\newF*' not found.
>> mkdir(nextname(fullfile(D,'newFolder'),'1','',true))
>> dir(fullfile(D,'newF*'))
newFolder1
>> mkdir(nextname(fullfile(D,'newFolder'),'1','',true))
>> dir(fullfile(D,'newF*'))
newFolder1 newFolder2
>> mkdir(nextname(fullfile(D,'newFolder'),'1','',true))
>> dir(fullfile(D,'newF*'))
newFolder1 newFolder2 newFolder3