Matlab 3d-matrix

匆匆过客 提交于 2019-12-30 08:33:42

问题


I have to create a very big 3D matrix (such as: 500000x60x60). Is there any way to do this in matlab?

When I try

omega = zeros(500000,60,60,'single');

I get an out-of-memory error.

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?


回答1:


Matlab only has support for sparse matrices (2D). For 3D tensors/arrays, you'll have to use a workaround. I can think of two:

  1. linear indexing
  2. cell arrays

Linear indexing

You can create a sparse vector like so:

A = spalloc(500000*60*60, 1, 100); 

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.

Then you can refer to elements as if it is a 3D array like so:

A(sub2ind(size(A), i,j,k)) 

where i, j and k are the indices to the 1st, 2nd and 3rd dimension, respectively.

Cell arrays

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);

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}

where i, j and k are the indices to the 1st, 2nd and 3rd dimension, respectively.




回答2:


Since your matrix is sparse, try to use ndsparse (N-dimensional sparse arrays FEX)



来源:https://stackoverflow.com/questions/12643279/matlab-3d-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!