【问题标题】:Is there a more efficient/less time demanding way to change this matrix size?是否有更有效/更少时间要求的方法来更改此矩阵大小?
【发布时间】:2022-11-14 23:10:54
【问题描述】:

让我们考虑一下我的 Matlab 代码:

T = 250;
N = 10;
B = 5000;

% starting matrix
Matrix1 = rand(T,N*3,B);
% ending matrix
Matrix2 = nan(T,B*3,N);

% the loop is very slow
for n = 1:(N*3)
    for b = 1:B
        if n <= 10
            Matrix2(:,b,n) = Matrix1(:,n,b);
        elseif n <= 20
            Matrix2(:,b + B,n - N) = Matrix1(:,n,b);
        else
            Matrix2(:,b + B + B,n - N - N) = Matrix1(:,n,b);
        end
    end
end

有没有更有效或更省时的方法来获得第二个矩阵?

【问题讨论】:

  • 分配左侧的所有“Matrix1”变量都应该是“Matrix2”吗?
  • 不是最终的好解决方案(实际上可能涉及reshape,实际上可能只是reshape,但您的if/else 基本上是Matrix2(:, b*(i-1)*B+1, n*(i-1)*N+1),对于任意数量的拆分,在这种情况下为3。
  • 分配到正确的矩阵可能会使此代码更快一些。但是您可以使用reshapepermute 一次性完成此操作,或者分别复制三个块。当然没有必要像这样循环nb
  • @GrapefruitIsAwesome 是的所有元素

标签: matlab loops matrix resize


【解决方案1】:

编辑

循环可以写成reshapepermute 操作的组合:

Matrix2 = reshape(permute(reshape(Matrix1, T,N,3,B), [1 4 3 2]), T, B*3, N);

主要答案可用于将循环转换为矢量化形式:

这是一个矢量化的解决方案:

n = 1:(N*3);
b = 1:B;
% split n based on 3 conditions
n1 = n(n <= 10);
n2 = n(n > 10 & n <= 20);
n3 = n(n > 20);
% the order of dimensions of both arrays should match
Matrix11 = permute(Matrix1, [1,3,2]);

Matrix2(:, b, n1) = Matrix11(:, b, n1); 
Matrix2(:, b + B, n2 - N) = Matrix11(:, b, n2);
Matrix2(:, b + B + B, n3 - N - N) = Matrix11(:, b, n3);

索引n应该根据三个条件分为三个部分。还需要置换Matrix1,使其维度的顺序与Matrix2 的顺序相匹配,以确保矢量化分配正常工作。然而,由于Matrix1 的维度顺序发生了变化,因此在提取Matrix11 的子集时需要重新排序索引位置。

等同于 permute 可以应用于每个作业

n = 1:(N*3);
b = 1:B;

n1 = n(n <= 10);
n2 = n(n > 10 & n <= 20);
n3 = n(n > 20);

Matrix2(:, b, n1) = permute(Matrix1(:, n1, b),[1 3 2]); 
Matrix2(:, b + B, n2 - N) = permute(Matrix1(:, n2, b),[1 3 2]);
Matrix2(:, b + B + B, n3 - N - N) = permute(Matrix1(:, n3, b),[1 3 2]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-14
    • 2016-11-25
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2019-06-29
    相关资源
    最近更新 更多