如何在 Matlab 中使用 cell2mat 循环将单元格转换为矩阵?

How can I convert a cell to matrices by loop using with cell2mat in Matlab?

我有一个包含 361 x 3D 矩阵的单元格 A(361,1)。矩阵的第一维和第二维相同,但第三维的长度不同。

所以单元格 A 看起来像:

A={(464x201x31);(464x201x28);(464x201x31);(464x201x30)....}

我想通过循环从这个单元格中取回矩阵。我尝试了以下解决方案:

for i=1:361;
M(i)=cell2mat(A(i));
end 

但是我得到以下错误:

Subscripted assignment dimension mismatch.

1. 如果您想 访问每个 3D 数组 与元胞数组分开,您总是可以使用 A{i}获取每个 3D 矩阵。

示例:

%// Here i have taken example cell array of 1D matrix 
%// but it holds good for any dimensions

A = {[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6]};

>> A{1}

ans =

 1     2     3

2. 相反,如果您想 连接 所有这些 3D 矩阵 成一个三维矩阵,这是一种方法

out = cell2mat(permute(A,[1 3 2]));  %// assuming A is 1x361 from your example

out = cell2mat(permute(A,[3 2 1]));  %// assuming A is 361x1 

3. 相反,如果你想 NaN pad 他们 获得 4D 矩阵,

maxSize = max(cellfun(@(x) size(x,3),A));   
f = @(x) cat(3, x, nan(size(x,1),size(x,2),maxSize-size(x,3)));  
out = cellfun(f,A,'UniformOutput',false); 
out = cat(4,out{:}); 

样本运行:

>> A

A = 

[3x4x2 double]    [3x4x3 double]    [3x4x4 double]

>> size(out)

ans =

 3     4     4     3 
%// note the first 3 size. It took the max size of the 3D matrices. i.e 3x4x4
%// Size of 4th dimension is equal to the no. of 3D matrices   

您可以通过 out(:,:,:,i)

访问每个 3D 矩阵