我有一个三维的单元格数组,即16x10x3,我希望:,:,1
:,:,2
和:,:,3
中的所有值都被提取到每个矩阵的列中。
我考虑过预先分配一个矩阵,然后运行一个基本的循环,例如:
for m=1:3
mat(:,m) = ([a{:,:,m}]);
end
有没有更有效的方法来做到这一点而不必依赖循环?
编辑::,:,1/2/3之间有不同数量的值。
答案 0 :(得分:1)
现在是时候进入bsxfun
了!这是实施 -
%// Get the number of elements in each column of the input cell array
lens = sum(cellfun('length',reshape(a,[],size(a,3))),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
mat = 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
mat(mask) = [a{:}]