## How do you catalogue/index a matrix to be concatenated into a 3D matrix?

### Sarah (view profile)

on 13 Sep 2018
Latest activity Edited by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 13 Sep 2018
I want to stitch together a series of images (2D matrices) into a 3D image (3D matrix). Preferably, this would be done within a for loop, however I don't understand how to catalogue (or is the term "index?") each matrix. And I don't know how to concatenate the catalogued/indexed images within the for loop.
% n = specified number of images;
% do you need an example image to answer this question?
for m = 1:n
figname = strcat('figure', m, '.png');
IM = imread(figname); % how do I catalogue/index here?
end
IM3d = cat(3, ...) % how do I make the 3D matrix here?

#### 1 Comment

Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 13 Sep 2018
"I want to stitch together a series of images (2D matrices) ..."
Are the images really 2D? Most color and grayscale image are stored as RGB, which are 3D arrays:

R2018a

on 13 Sep 2018
Edited by Greg

### Greg (view profile)

on 13 Sep 2018

You actually had a pretty good start. The only piece of your attempt that wasn't going to work was that you weren't concatenating inside the loop. Since each iteration loaded a new filename and overwrote IM, you only ended up with 1 frame outside the loop.
You could have added IM = []; before the loop then IM = cat(3,IM,imread(…)); inside the loop, but this leads to performance issues. Also, it requires all images to be exactly the same size in pixels.
The following code pre-allocates, and allows images to be different sizes.
filenames = strcat('figure', num2str(1:n)', '.png');
info = cellfun(@imfinfo,filenames);
widths = [info.Width]';
heights = [info.Height]';
IM3d = NaN(max(heights),max(widths),n);
for m = 1:n
w = widths(m);
h = heights(m);
end
"Catalogue" isn't a MATLAB term (at least not in any context related to this question). Your approach doesn't technically use "indexing," but that is an accurate term. "Concatenate" is the appropriate word. My commands inside the for loop use indexing.
P.S. I can't launch MATLAB to make sure I don't have any silly syntax errors, but the above approach is at least pretty close. If it doesn't work for you, let me know and I'll update.

### Stephen Cobeldick (view profile)

on 13 Sep 2018
Edited by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 13 Sep 2018

I would recommend following the examples in the MATLAB documentation:
In your case you can simply do this:
N = ... number of images
C = cell(1,N); % preallocate cell array.
for k = 1:N
figname = sprintf('figure%d.png',k);