performance - 将矩阵从 3d reshape 为 2d 保持行

标签 performance matlab indexing reshape

我正在将 3d 矩阵转换为 2d 矩阵。这是形状变换:[n x m x o] -> [n*o x m]。

矩阵的元素与行相关。因此,要求在结果矩阵中具有相同的行。

A = rand(2,2,3);

这样做:

C = reshape(A, 2*3, 2);

不保留 A 中的行。

所以我这样做:

B = zeros(size(A,1)*size(A,3),size(A,2));
first_indice = 1;
for i = 1:size(A,3)
    B(first_indice:size(A,1)*i,:)=A(:,:,i);
    first_indice = first_indice + size(A,1);
end

是否有更有效的方法使用 reshape ?

非常感谢!

最佳答案

reshape 组合从第一维开始的矩阵元素。因此,解决方案是在 reshape 之前置换尺寸。在您的情况下,它应该如下所示:

% A is the input matrix of dimensions (n x m x o).
B = ipermute(A, [1 3 2]);
C = reshape(B, n*o, m);

关于performance - 将矩阵从 3d reshape 为 2d 保持行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8655878/

相关文章:

indexing - 在EdgeDB中定义唯一索引

javascript - 根据变量的值范围,是否有比使用 if-else 语句更快/更有效的方法来调用不同的函数?

MySQL - 昂贵的子查询

php - MongoDB 在写入密集型应用程序中的性能异常差

c - 由 MATLAB MEX 函数中的 "optimised out"值引起的 GCC 段错误

matlab - Latex变量自动化: writing variables for Latex directly from Stata and MATLAB

matlab - 使用 sym.int 时出错输入参数过多

oracle - 在现有表 Oracle 上创建索引

Java垃圾回收 "real"时间比 "user"大很多 +"system"

Excel VBA 如何使代码更高效并花费更少的时间