[英]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? 有没有一种方法可以在Matlab的循环中使用end
索引在三维空间中扩展3D数组?
In 2D it can be done like 在2D中可以像
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). 但是在3D中,相同的东西将不起作用,因为a(1,1,end)
会尝试在第一次迭代中索引a(1,1,1)
(而不是人们可能期望的a(1,1,0)
)。 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: 看来end
的a
在第三维度比前两个处理方式稍有不同:
>> 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? 我是否想了解end
索引在这里的工作方式?
If you know the size of g(x), initialize im
to an empty 3d-array: 如果知道g(x)的大小,请将im
初始化为空的3d数组:
im = zeros(n, m, 0); %instead of im = [];
I think your code should work now. 我认为您的代码现在应该可以工作了。
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! 这样,您不必分配新的内存并在每次调整大小时复制整个矩阵im
!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.