将 0 添加到元胞数组,使每列包含相同数量的条目 - MATLAB

Adding 0's to cell array such that each column contains an equal number of entries - MATLAB

我有一个 16x100(大小不一)的元胞数组,我想将它的每一列提取到矩阵的一列中。当元胞数组的每一列包含相同数量的条目时,我可以使用:

elem = numel([dist{:,1}]);
repeat = size(dist,2);
data = zeros(elem,repeat);  
for k=1:repeat
  results(:,k) = [dist{:,k}]';
end

然而,在某些情况下,数量不相等,因此 returns 错误:

Subscripted assignment dimension mismatch.

最好的解决方法是什么?有没有办法添加零来均衡条目数?

这里是 bsxfun's masking capability 的完美设置!

现在,我假设您的数据已按照 -

中所述进行设置

要解决用零填充 "empty spaces" 的情况,您可以设置一个输出数组,每列中的元素数量最多,然后用输入元胞数组中的值填充有效空间,使用 bsxfun 创建的逻辑掩码检测到有效空间。继续阅读下面列出的代码中内嵌的注释,找出解决它的确切想法 -

%// Get the number of elements in each column of the input cell array
lens = sum(cellfun('length',a),1)

%// Store the maximum number of elements possible in any column of output array
max_lens = max(lens)  

%// Setup output array, with no. of rows as max number of elements in each column
%// and no. of columns would be same as the no. of columns in input cell array 
results = zeros(max_lens,numel(lens))

%// Create as mask that has ones to the "extent" of number of elements in
%// each column of the input cell array using the lengths
mask = bsxfun(@le,[1:max_lens]',lens)  %//'

%// Finally, store the values from input cell array into masked positions
results(mask) = [a{:}]