我正在处理一个n维矩阵(它被存储为一个一维数组),我希望在它的维度中重新排序,这样领先维度现在是最后一个维度。
例如:如果维数(A)=3x4x5x6,我想将其改为4x5x6x3,这类似于二维矩阵的转置函数。
它可以用Matlab中的置换函数对n维矩阵A实现。
A=permute(A,[2:n 1])我怎么能用C语言做呢?
我不是要重塑矩阵,而是实际移动元素,以得到下一个维度作为主导维度。
置换可以定义为
B = PERMUTE(A,ORDER) rearranges the dimensions of A so that they
% are in the order specified by the vector ORDER. The array produced
% has the same values as A but the order of the subscripts needed to
% access any particular element are rearranged as specified by ORDER.
% For an N-D array A, numel(ORDER)>=ndims(A). All the elements of
% ORDER must be unique.发布于 2014-07-23 18:07:43
我不想尝试就地执行,但是复制到一个新的数组只会比你已经做的要复杂一些。我为我的apl解释器编写了类似的函数。
如果有可以将索引列表和维度列表转换为单个一维索引的操作,则相反,将单个索引和维度列表转换为索引列表;然后只需遍历1D数组,使用源维度生成索引列表,对索引列表应用置换,使用目标维度转换回单个索引,并将结果存储在目标数组中。
dest dimensions = permute source dimensions
for each element in source
generate source indices from source index and source dimensions
dest indices = permute source indices
generate dest index from dest indices and dest dimensions
dest[dest index] = source[source index]伪代码描述了算法,但这里有一个实现:array.c:transposea()。该函数更改了它的参数,因此对于上面的语义,它应该先调用clone(),然后调用copy(),以便实际移动数据并保持原始数据不受干扰。
https://stackoverflow.com/questions/24917388
复制相似问题