gpt4 book ai didi

c - 如何在C中重新排序n维矩阵的维度? (类似于排列(A,[2 :n 1]) in Matlab )

转载 作者:行者123 更新时间:2023-11-30 17:30:50 26 4
gpt4 key购买 nike

我正在处理一个 n 维矩阵(存储为一维数组),我希望对其维度进行重新排序,以便前导维度现在是最后一个维度。

eg. if Dimensions(A) = 3 x 4 x 5 x 6 , I would want to change it to 4 x 5 x 6 x 3. This is similar to a transpose function for a 2-D matrix.

可以使用Matlab中的permute函数来实现对于n维矩阵A。我想要以下转换

A=permute(A,[2:n 1])

我怎样才能用C语言做到这一点?

附注我并不是要 reshape 矩阵,而是要实际移动元素以获得下一个维度作为主导维度。

排列可以定义为

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.

最佳答案

我不想尝试就地执行此操作,但复制到新数组会比您已经执行的操作稍微复杂一些。我为我的 apl 解释器编写了一个类似的函数。

如果您的操作可以将索引列表和维度列表转换为单个一维索引,反之亦然,将单个索引和维度列表转换为索引列表;然后,您只需迭代一维数组,使用源维度生成索引列表,将排列应用于索引列表,使用目标维度转换回单个索引并将结果存储在目标数组中。

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() ,以实际移动数据并保持原始数据不受干扰。

关于c - 如何在C中重新排序n维矩阵的维度? (类似于排列(A,[2 :n 1]) in Matlab ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24917388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com