【问题标题】:Adding 0's to cell array such that each column contains an equal number of entries - MATLAB向元胞数组添加 0,以使每列包含相等数量的条目 - MATLAB
【发布时间】:2015-02-26 09:57:51
【问题描述】:

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

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

但在某些情况下,数字不相等,因此会返回错误:

Subscripted assignment dimension mismatch.

解决这个问题的最佳方法是什么?有没有办法添加零以使条目数量相等?

【问题讨论】:

  • 元胞数组包含什么?发布一个最小示例dist 和所需的输出

标签: matlab matrix cell-array


【解决方案1】:

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

现在,我假设您的数据已按照您的 previous question 中所述设置 -

为了解决用零填充“空白空间”的情况,您可以设置一个输出数组,每列中的元素数量最多,然后用输入元胞数组中的值填充有效空间,有效由bsxfun 创建的逻辑掩码检测到的空格。继续阅读下面列出的代码中内联的 cmets,找出解决问题的确切思路 -

%// 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{:}]

【讨论】:

  • 哇!一段时间以来,我一直在寻找学习如何使用 bsxfun 的借口。谢谢!
  • @AnnaSchumann 嘿!你必须!:) 它是在 MATLAB 上做几乎任何事情的最佳工具!
猜你喜欢
  • 1970-01-01
  • 2015-06-22
  • 1970-01-01
  • 2023-03-03
  • 2017-10-02
  • 1970-01-01
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多