首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对C中n维矩阵的维数进行重新排序?(类似于Matlab中的置换(A,[2:n1]))

如何对C中n维矩阵的维数进行重新排序?(类似于Matlab中的置换(A,[2:n1]))
EN

Stack Overflow用户
提问于 2014-07-23 17:46:09
回答 1查看 1.7K关注 0票数 2

我正在处理一个n维矩阵(它被存储为一个一维数组),我希望在它的维度中重新排序,这样领先维度现在是最后一个维度。

例如:如果维数(A)=3x4x5x6,我想将其改为4x5x6x3,这类似于二维矩阵的转置函数。

它可以用Matlab中的置换函数对n维矩阵A实现。

代码语言:javascript
复制
A=permute(A,[2:n 1])

我怎么能用C语言做呢?

我不是要重塑矩阵,而是实际移动元素,以得到下一个维度作为主导维度。

置换可以定义为

代码语言:javascript
复制
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.
EN

回答 1

Stack Overflow用户

发布于 2014-07-23 18:07:43

我不想尝试就地执行,但是复制到一个新的数组只会比你已经做的要复杂一些。我为我的apl解释器编写了类似的函数。

如果有可以将索引列表和维度列表转换为单个一维索引的操作,则相反,将单个索引和维度列表转换为索引列表;然后只需遍历1D数组,使用源维度生成索引列表,对索引列表应用置换,使用目标维度转换回单个索引,并将结果存储在目标数组中。

代码语言:javascript
复制
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(),以便实际移动数据并保持原始数据不受干扰。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24917388

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档