For 循环将矩阵拆分为相等大小的子矩阵 [英] For loop to split matrix to equal sized sub-matrices
问题描述
给定一个大小为 400x400
的方阵,我将如何使用 for 循环将其拆分为 20x20
的组成子矩阵?我什至想不出从哪里开始!
Given a square matrix of say size 400x400
, how would I go about splitting this into constituent sub-matrices of 20x20
using a for-loop? I can't even think where to begin!
我想我想要这样的东西:
I imagine I want something like :
[x,y] = size(matrix)
for i = 1:20:x
for j = 1:20:y
但我不确定我将如何进行.想法?
but I'm unsure how I would proceed. Thoughts?
推荐答案
嗯,我知道发布者明确要求 for
循环,而 Jeff Mather 的回答正好提供了这一点.
Well, I know that the poster explicitly asked for a for
loop, and Jeff Mather's answer provided exactly that.
但我仍然很好奇是否有可能在没有循环的情况下将矩阵分解为给定大小的瓦片(子矩阵).如果其他人也很好奇,这就是我想出的:
But still I got curious whether it is possible to decompose a matrix into tiles (sub-matrices) of a given size without a loop. In case someone else is curious, too, here's what I have come up with:
T = permute(reshape(permute(reshape(A, size(A, 1), n, []), [2 1 3]), n, m, []), [2 1 3])
将二维数组A
转化为三维数组T
,其中每个二维切片T(:, :, i)
是 m
x n
大小的图块之一.第三个索引以标准的 Matlab 线性顺序枚举瓦片,首先是瓦片行.
transforms a two-dimensional array A
into a three-dimensional array T
, where each 2d slice T(:, :, i)
is one of the tiles of size m
x n
. The third index enumerates the tiles in standard Matlab linearized order, tile rows first.
变体
T = permute(reshape(A, size(A, 1), n, []), [2 1 3]);
T = permute(reshape(T, n, m, [], size(T, 3)), [2 1 3 4]);
使 T
成为一个四维数组,其中 T(:, :, i, j)
给出了带有切片索引 i, j
的二维切片代码>.
makes T
a four-dimensional array where T(:, :, i, j)
gives the 2d slice with tile indices i, j
.
提出这些表达式感觉有点像解决滑动拼图.;-)
Coming up with these expressions feels a bit like solving a sliding puzzle. ;-)
这篇关于For 循环将矩阵拆分为相等大小的子矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!