将 3D 元胞数组中的数据提取到 2D 矩阵中 - MATLAB
Extracting data from a 3D cell array into a 2D Matrix - MATLAB
我有一个三维元胞数组,即 16x10x3,我希望将 :,:,1
:,:,2
和 :,:,3
中的所有值分别提取到矩阵的列中.
我考虑过预先分配一个矩阵,然后 运行 一个基本循环,例如:
for m=1:3
mat(:,m) = ([a{:,:,m}]);
end
有没有更有效的方法来做到这一点而不必依赖循环?
编辑::,:,1/2/3 之间有不同数量的值。
是时候进入 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{:}]
我有一个三维元胞数组,即 16x10x3,我希望将 :,:,1
:,:,2
和 :,:,3
中的所有值分别提取到矩阵的列中.
我考虑过预先分配一个矩阵,然后 运行 一个基本循环,例如:
for m=1:3
mat(:,m) = ([a{:,:,m}]);
end
有没有更有效的方法来做到这一点而不必依赖循环?
编辑::,:,1/2/3 之间有不同数量的值。
是时候进入 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{:}]