Take the 2-minute tour ×

I am trying to do my first project in MATLAB and so far I try to load a sequence of images from a directory and store them in one object.

The images are small and they are quite few < 100, so memory is not a problem.

I would optimally store them in a 3 dimensional array, but I don't know how to do it.

Can you tell me how to load images and store all them in a stack?

So far here is the code I have written:

function image = load_image_array(dir, start, finish)
    for i = start:finish

        filename = [ dir '/' sprintf('%08d', i) '.jpg' ];
        image = importdata( filename, 'jpg' );

        figure( i );
        imagesc( image );


Do you think it is a good idea to preallocate the array in advance? Also, is 3 dimensional array a good idea? I would like to have RGB images, do I need to have 3 stacks or a 4 dimensional array for this?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

Assuming they're all the same size, storing them in a stack is as simple as:

imageStack(i,:,:) = image;
imagesc( squeeze(imageStack(i,:,:)) );

If they're not the same size, just use a cell array:

imageStack{i} = image;
imagesc( imageStack{i} );

My syntax may be off for the cell array, test it out and play with it. I'll try to remember to doublecheck it when I get to work later.

share|improve this answer
Thanks. They are the same size. –  zsero Oct 18 '11 at 15:41
Why the squeeze? –  DogDog Nov 17 '11 at 21:00
@Apoc - Without the squeeze, matlab treats the variable as a 3-D matrix with dimensionality 1xNxM. With the squeeze, it's a 2-D matrix of size NxM. Many matlab functions require a 2-D matrix, and squeeze often comes in handy when pulling slices out of a stack of images. –  eykanal Dec 13 '11 at 19:29

you could look up this link. Makes it very easy!


share|improve this answer

Your Answer


