我在<1x2细胞>。我想排列这些数组。当然,我可以使用一个循环来排列每一个,但有没有办法在不使用循环的情况下一次完成任务?
示例:
>> whos('M')
Name Size Bytes Class Attributes
M 1x2 9624 cell
>> permute(M,p_matrix)
这不会在M.内排列两个阵列的内容
我可以使用类似的东西:
>> for k=1:size(M,2), M{k} = permute(M{k},p_matrix); end
但我不喜欢使用循环。
谢谢。
这似乎有效-
num_cells = numel(M) %// Number of cells in input cell array
size_cell = size(M{1}) %// Get sizes
%// Get size of the numeric array that will hold all of the data from the
%// input cell array with the second dimension representing the index of
%// each cell from the input cell array
size_num_arr = [size_cell(1) num_cells size_cell(2:end)]
%// Dimensions array for permuting with the numeric array holding all data
perm_dim = [1 3:numel(size_cell)+1 2]
%// Store data from input M into a vertically concatenated numeric array
num_array = vertcat(M{:})
%// Reshape and permute the numeric array such that the index to be used
%// for indexing data from different cells ends up as the final dimension
num_array = permute(reshape(num_array,size_num_arr),perm_dim)
num_array = permute(num_array,[p_matrix numel(size_cell)+1])
%// Save the numeric array as a cell array with each block from
%// thus obtained numeric array from its first to the second last dimension
%// forming each cell
size_num_arr2 = size(num_array)
size_num_arr2c = num2cell(size_num_arr2(1:end-1))
M = squeeze(mat2cell(num_array,size_num_arr2c{:},ones(1,num_cells)))
一些快速测试表明,mat2cell
将被证明是瓶颈,因此,如果您不介意索引到中间数值数组变量num_array
,并使用它的最后一个维度对M进行等效索引,那么这种方法可能会很有用。
现在,如果您想保留单元格格式,另一种方法是使用arrayfun
,假设M
的每个单元格都是4D
数字数组-
M = arrayfun(@(x) num_array(:,:,:,:,x),1:N,'Uniform',0)
就性能而言,这似乎比使用mat2cell
要好得多。
请注意,arrayfun
不是一个矢量化的解决方案,因为它肯定在幕后使用循环,而且mat2cell
似乎在其源代码中使用for循环,所以请记住所有这些问题。