Search code examples
arraysmatlabmatrix-indexing

Grow 3D array in Matlab


Is there a way to grow a 3D array in the third dimension using the end index in a loop in Matlab?

In 2D it can be done like

a = [];
for x = y
   a(end + 1, :) = f(x);
end

But in 3D the same thing will not work as a(1,1,end) will try to index a(1,1,1) the first iteration (not a(1,1,0) as one might expect). So I can't do

im = [];
for x = y
   im(:, :, end + 1) = g(x);
end

It seems the end of a in third dimension is handled a bit differently than in the first two:

>> a = [];
>> a(end,end,end) = 1
Attempted to access a(0,0,1); index must be a positive integer or logical.

Am I missing something about how end indexing works here?


Solution

  • What you're asking...

    If you know the size of g(x), initialize im to an empty 3d-array:

    im = zeros(n, m, 0);   %instead of im = [];
    

    I think your code should work now.

    A better way...

    Another note, resizing arrays each iteration is expensive! This doesn't really matter if the array is small, but for huge matrices, there can be a big performance hit.

    I'd initialize to:

    im = zeros(n, m, length(y));
    

    And then index appropriately. For example:

    i = 1;
    for x = y
       im(:, :, i) = g(x);
       i = i + 1;
    end
    

    This way you're not assigning new memory and copying over the whole matrix im each time it gets resized!