MATLAB Answers

Creating a 3D array out of multiple 2D arrays

721 views (last 30 days)
Med_Imager
Med_Imager on 13 Feb 2012
Commented: Steven Lord on 22 Mar 2021 at 15:28
I have 10 masks that are 256 x 256 each. These masks are for 10 respective slices, so I want to combine them and make a 3D array ( 256x256x10). How do I do this? Ideas? Thanks!

Accepted Answer

Sean de Wolski
Sean de Wolski on 13 Feb 2012
cat(3,mask1,mask2,...)
doc cat %for more info
  2 Comments
Steven Lord
Steven Lord on 22 Mar 2021 at 15:28
Revise your code so it doesn't create 100 individual variables. Preallocate the array to be the desired size from the start and fill it in.
A = magic(4);
B = repmat(A, [1 1 5]); % or
C = zeros(4, 4, 5);
for k = 1:5
B(:, :, k) = A^k;
C(:, :, k) = A^k;
end

Sign in to comment.

More Answers (2)

Med_Imager
Med_Imager on 13 Feb 2012
You can also do
Mask_3D(:,:,1)=Mask_1
for index=1:10
eval(['Mask_3D(:,:,index)=Mask_' num2str(index)';']);
end

Kris Hoffman
Kris Hoffman on 20 Jul 2020
I just had this exact problem (even with the same dimensions)
If the masks are all in one cell array,
A = cat(3,YourMaskArrayHere{:})
Produces a 256x256x10 uint16 array.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!