1

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.

0

1 Answer 1

2

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:

String array

Characters and Strings

Sign up to request clarification or add additional context in comments.

3 Comments

I appreciate your help but even using your example I have returned to my Error using mkdir Arguments must contain a character vector. error. Do you know why this might be?
@SolebaySharp my bad. you have to convert names(name) to char: char(names(name)) or simply use cell array. I have updated my answer to reflect the change.
Thank you I have been working on this for some time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.