首页 > 解决方案 > 将单元格转换为 4D 数组

问题描述

我的数据以某种形式出现,但我需要另一种形式。我已经尝试过reshapepermute但是,我没有达到预期的结果。

输入:

A = {5 x 1} 元胞数组,其中每个元胞都是{300 x 18 single}.

预期输出:

大小为 18 x 300 x 1 x5 的 4D 数组:

A( 1,  1,1,1) = 0.5
A( 1,  2,1,1) = 0.7
....
A( 1,300,1,1) = 0.8
...
A(18,300,1,1) = 0.99
...
...
...
A(18,300,1,5) = 0.89

(以上数值是随机的)

这是我的尝试,

z = cellfun(@(X) permute(X,[3 2 1]),A,'UniformOutput',false);

这导致

z =
  5×1 cell array
    {1×18×300 single}
    {1×18×300 single}
    {1×18×300 single}
    {1×18×300 single}
    {1×18×300 single}

标签: arraysmatlabmultidimensional-arrayreshapecell-array

解决方案


我认为permute并且reshape 要走的路。这是我的做法:

function z = q56764340(A)
if ~nargin
  %% Generate some data:
  A = reshape(num2cell(zeros(300,18,5,'single'), [1,2]),[], 1);
  %{
  A =
    5×1 cell array
      {300×18 single}
      {300×18 single}
      {300×18 single}
      {300×18 single}
      {300×18 single}
  %}
end

%% Convert to a 4d numeric array:
z = permute( ...                  this does 300x18x1x5 -> 18x300x1x5
      cell2mat( ...               this does 1x1x1x5 -> 300x18x1x5
        reshape(A,1,1,1,[])), ... this does 5x1 -> 1x1x1x5
      [2,1,3,4]);

推荐阅读