将0添加到单元格数组中,以使每一列包含相等数量的条目-MATLAB [英] Adding 0's to cell array such that each column contains an equal number of entries - MATLAB

查看:140
本文介绍了将0添加到单元格数组中,以使每一列包含相等数量的条目-MATLAB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a 16x100 (varies in size) cell array and I would like to extract each of it's columns into a column of a matrix. When each column of the cell array contains an identical number of entries I can use:

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

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

However there are some instances where there are not an equal number thus it returns the error:

Subscripted assignment dimension mismatch.

解决此问题的最佳方法是什么?有没有一种方法可以添加零以使条目数相等?

What is the best way around this? Is there a way to add zeroes to equalise the number of entries?

推荐答案

bsxfun's masking capability

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

Now, I am assuming your data is setup as described in your previous question -

要解决用零填充空空间"的情况,您可以设置一个输出数组,在每列中使用最大数量的元素,然后用输入单元格数组中的值填充有效空间,并在其中填充有效的空格.由bsxfun创建的逻辑掩码检测到的空格.阅读下面列出的代码中内联的注释,以找到解决该问题的确切思路-

To solve the case of filling up "empty spaces" with zeros, you can setup an output array with maximum possible number of elements in each column and then fillup the valid spaces with the values from the input cell array, with the valid spaces being detected by the logical mask created with bsxfun. Read on through the comments inlined within the code listed next to find out the exact ideas on solving it -

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

这篇关于将0添加到单元格数组中,以使每一列包含相等数量的条目-MATLAB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆