将向量的元素存储到单元格中

Store elements of vector into cells

我有一个数字向量,我想将每四个元素存储到一个单元格中。所以前 4 个元素将进入第一个单元格,接下来的四个元素将进入第二个单元格,依此类推。

有没有不用循环的方法?谢谢!

您可以使用 mat2cell 来做到这一点

data = 1:16;
output = mat2cell(data, 1, (numel(data)/4) * ones(1,4))

%   output{1} =
%   
%      1   2   3   4
%   
%   output{2} =
%   
%      5   6   7   8
%   
%   output{3} =
%   
%       9   10   11   12
%   
%   output{4} =
%   
%      13   14   15   16

我个人觉得输入格式有点混乱。另一种方法是将矩阵重塑为 4 行,然后使用 num2cell 将每一列分成它自己的单元格。

data = 1:16;
output = num2cell(reshape(data, 4, []), 1)