向量化矩阵行块的混洗

时间:2019-07-02 10:32:33

标签: matlab matrix vectorization shuffle

我有一个名为5x15的简单mat_orig矩阵。我想将此矩阵划分为不重叠的块,从而每个块的长度为3。这等效于将三个不重叠的行放入一个块中(即,有5个大小为3x5的块)。 / p>

然后我想将mat_orig改组并生成一个新矩阵。我正在使用randi随机绘制五个块。

我使用下面的代码成功完成了任务。但是,我想知道是否可以摆脱for循环?我可以应用矢量化吗?

mat_orig = reshape(1:75, 5, 15)';

block_length = 3;

num_blocks = size(mat_orig, 1) / block_length;

rand_blocks = randi(num_blocks, num_blocks, 1);

mat_shuffled = nan(size(mat_orig));

for r = 0 : num_blocks - 1
    start_row_orig = r * block_length + 1;
        end_row_orig = r * block_length + block_length;
    start_row_random_blocks = ...
        rand_blocks(r + 1) * block_length - block_length + 1;
    end_row_random_blocks = ...
        rand_blocks(r + 1) * block_length;

    mat_shuffled(start_row_orig:end_row_orig, :) = ...
        mat_orig(start_row_random_blocks:end_row_random_blocks, :);
end

1 个答案:

答案 0 :(得分:3)

您可以通过隐式扩展来执行此操作,以创建块的索引,有关详细信息,请参见代码注释。

mat_orig = reshape(1:75, 5, 15)';
block_length = 3;
num_blocks = size(mat_orig,1) / block_length;

% Get the shuffle order (can repeat blocks)
shuffIdx = randi( num_blocks, num_blocks, 1 ).';
% Expand these indices to fill the blocks
% This uses implicit expansion to create a matrix, and 
% will only work in R2016b or newer.
% For older versions, use 'bsxfun'
shuffIdx = block_length * shuffIdx - (block_length-1:-1:0).';
% Create the shuffled output
mat_shuffled = mat_orig( shuffIdx(:), : );