Reputation: 533
I'm trying to just loop through some folders using a list of strings in Matlab and everything I've tried hasn't worked.
For instance, if I had three names, all I'd want is to loop through some folders like this:
names = ['Tom', 'Dick', 'Harry']
SourceDir = /path/to/my/files
for name = 1:length(names)
mkdir SourceDir, "/things_belonging_to_", names(name), "/new_things"
OutputDir = (SourceDir, "/things_belonging_to_", names(name), "/new_things")
cd "/things_belonging_to_", names(name), "/oldthings"
% do other stuff that will be dumped in OutputDir
end
I've tried using {}
instead of []
, I tried to use sprintf
and fullfile
. All I want is a really boring for-loop and I cannot seem to find/understand the documentation that shows me how to use strings in the mkdir
or cd
command. I always end up with string input not supported
or Arguments must contain a character vector
.
Upvotes: 1
Views: 3684
Reputation: 3793
names = ['Tom', 'Dick', 'Harry']
makes names
a string rather than a string array. To use string array, make sure you have MATLAB 2016b+ where you can use double quotation mark:
names = ["Tom", "Dick", "Harry"]
Otherwise, use cell array:
names = {'Tom', 'Dick', 'Harry'}
And access the elements using curly bracket and index:
names{1} % Tom
names{2} % Dick
There are also a number of other mistakes in your code:
SourceDir = '/path/to/my/files'
mkdir([SourceDir, '/things_belonging_to_', char(names(name)), '/new_things'])
OutputDir = [SourceDir, '/things_belonging_to_', char(names(name)), '/new_things']
cd(['/things_belonging_to_', char(names(name)), '/oldthings'])
In MATLAB you can use square bracket []
to concatenate strings into one.
All in one:
names = {'Tom', 'Dick', 'Harry'};
SourceDir = '/path/to/my/files';
for name = 1:length(names)
mkdir([SourceDir, '/things_belonging_to_', names{name}, '/new_things'])
OutputDir = [SourceDir, '/things_belonging_to_', names{name}, '/new_things']
cd(['/things_belonging_to_', names{name}, '/oldthings'])
% do other stuff that will be dumped in OutputDir
end
Further readings:
Upvotes: 2