Matlab 3D矩阵 [英] Matlab 3d-matrix
问题描述
我必须创建一个非常大的3D矩阵(例如:500000x60x60
).在matlab中有什么方法可以做到这一点?
I have to create a very big 3D matrix (such as: 500000x60x60
). Is there any way to do this in matlab?
当我尝试
omega = zeros(500000,60,60,'single');
我收到out-of-memory
错误.
稀疏函数不是选项,因为它仅适用于2D矩阵.那么对于高维矩阵,还有其他选择吗?
The sparse function is no option since it is only meant for 2D matrices. So is there any alternative to that for higher dimensional matrices?
推荐答案
Matlab仅支持稀疏矩阵(2D).对于3D张量/阵列,您必须使用一种解决方法.我可以想到两个:
Matlab only has support for sparse matrices (2D). For 3D tensors/arrays, you'll have to use a workaround. I can think of two:
- 线性索引
- 单元格数组
线性索引
您可以创建一个稀疏向量,如下所示:
Linear indexing
You can create a sparse vector like so:
A = spalloc(500000*60*60, 1, 100);
其中最后一个条目(100
)是指最终要分配给A
的非零数量.如果您事先知道此数量,则可以使A
的内存使用效率更高.如果您事先不知道它,只是使用接近它的数字,它仍然可以工作,但是A
最终会消耗比严格需要更多的内存.
where the last entry (100
) refers to the amount of non-zeros eventually to be assigned to A
. If you know this amount beforehand it makes memory usage for A
more efficient. If you don't know it beforehand just use some number close to it, it'll still work, but A
can consume more memory in the end than it strictly needs to.
然后,您可以像对待3D数组一样引用元素:
Then you can refer to elements as if it is a 3D array like so:
A(sub2ind(size(A), i,j,k))
其中,i
,j
和k
分别是第一维,第二维和第三维的索引.
where i
, j
and k
are the indices to the 1st, 2nd and 3rd dimension, respectively.
在3D张量/数组中将每个2D页面创建为单元格数组:
Create each 2D page in the 3D tensor/array as a cell array:
a = cellfun(@(x) spalloc(500000, 60, 100), cell(60,1), 'UniformOutput', false);
最后一个进入spalloc
的故事也是如此.然后像这样在3D中串联:
The same story goes for this last entry into spalloc
. Then concatenate in 3D like so:
A = cat(3, a{:});
然后您可以像这样引用各个元素:
then you can refer to individual elements like so:
A{i,j,k}
其中,i
,j
和k
分别是第一维,第二维和第三维的索引.
where i
, j
and k
are the indices to the 1st, 2nd and 3rd dimension, respectively.
这篇关于Matlab 3D矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!