mathpun
mathpun

Reputation: 39

Matlab-Iterating for loop with file string name

I am trying to read in 40 files to be executed by a certain function later in the code. There are 40 files named 'Part_#_D1', the # is a number between 1 and 40. How can I read them in here and iterate the function on it? I was trying to use the %d thing and use the i but it keeps failing. How am I using this incorrectly?

for i = 1:40
    img_part = imread('[/Users/cocosci/Desktop/H_All/,'Part_%d','/','Part_%d_D1.jpeg']'),i;
end

Upvotes: 0

Views: 46

Answers (1)

Suever
Suever

Reputation: 65460

You're just performing the horizontal concatenation of strings which doesn't suppoert any format specifiers. You can only use the %d format specifier (or any format specifier) when using either sprintf or fprintf. In your case, you'll want to use sprintf to generate a string.

for k = 1:40
    filename = sprintf('/Users/cocosci/Desktop/H_All/Part_%d/Part_%d_D1.jpeg', k, k);

    % Store each image in a cell array element
    img_part{k} = imread(filename);
end

And then you can access a particular image with

% Access the third image
img_part{3}

Also, consider using k as your loop index rather than i since i is a built-in for 0 + 1i.

Upvotes: 4

Related Questions