matlab 是否有更高效/更省时的方法来更改此矩阵大小?

wfsdck30  于 2022-11-15  发布在  Matlab
关注(0)|答案(1)|浏览(178)

让我们考虑一下我的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

有没有更高效或更省时的方法来到达第二个矩阵?

mdfafbf1

mdfafbf11#

编辑

循环可以写为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]);

相关问题