0

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

1 Answer 1

4

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.

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

7 Comments

Thanks!! Do I put that under the for loop, how do I get it to understand that i is 1-40?
@user3290443 I just updated it to include the explicit loop. Also, it will generate a new filename for each k value since that is inside of the loop.
Do I need just 1 k or 2? Since I used %d twice?
@user3290443 Oops you need two! I didn't see that second one when I posted initially. Updated now
(Yay, teamwork!) Ok cool, and then does it store all these in k? How can I see the values inside?
|

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.