我有一个简单的 5x15
矩阵,称为 mat_orig
。我想将此矩阵分为非重叠的块,每个块的长度为3。等于将三个非重叠的行放入一个块中(即有5个大小3x5
的块(。
然后,我想洗牌mat_orig
并生成一个新的矩阵。我正在使用randi
随机绘制五个块。
我成功地使用以下代码完成了任务。但是,我想知道我是否可以摆脱循环?我可以应用矢量化吗?
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
您可以使用隐式扩展来创建块的索引,请参阅代码注释以获取详细信息。
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(:), : );