I would like to concatenate two 3d arrays in a way that supports concatenation when the left hand side is empty. I'd expect the following code to work, but Matlab (2012b, and 2013a) seems to insert an extra zero matrix at the beginning.
a=[]
a =
[]
K>> a(:,:,(end+1):(end+2))=ones(2,2,2)
a(:,:,1) =
0 0
0 0
a(:,:,2) =
1 1
1 1
a(:,:,3) =
1 1
1 1
Is this a bug? What's the proper way of achieving this?
The problem is with the way you initialize
a
. Consider the following:This is explained in the documentation of the
size
function:The size is used by
end
to compute the index returned. To see this in action, we could overload theend
function with our custom version:@double\end.m
with the above function saved somewhere on the path, call:
You will see that the computed index
ind
returned byend
is 1, which is then incremented by oneend+1
resulting ina(:,:,2)=ones(2)
hence the extra space at the beginning is filled with zeros.To fix this, initialize the matrix correctly: