更改for循环中的顺序

时间:2014-03-05 20:16:36

标签: matlab for-loop

我有一个矩阵(大小为A和B;假设为100x100)并且想要填充大小为a和b的较小矩阵(或块)(假设为12x12)。

很明显,循环从“j”开始,然后进入下一行。实际上我想使用相同的循环,通过添加另一个变量来强制它首先完成列。任何想法我应该如何在以下循环中定义这个新变量来控制完成方向。

M = zeros(100,100);

for j = 1:12:100-12+1
    for i = 1:12:100-12+1
        block = rand(12,12);
        M(i:i+11, j:j+11) = block;
        imagesc(M); axis equal tight xy
        pause(.1)
    end;
end;

1 个答案:

答案 0 :(得分:1)

为什么不做呢

M = zeros(100,100);

for j = 1:12:100-12+1
    for i = 1:12:100-12+1
        block = rand(12,12);
        M(i:i+11, j:j+11) = block;
        imagesc(M); axis equal tight xy
        pause(.1)
    end;
end;

现在你将迭代我的第一个。

顺便提一下,我建议不要使用ij作为循环变量 - 它们会影响内置的sqrt(-1)虚数...

根据您的评论

更新,您似乎希望在外部循环中保留ij的顺序,并添加“其他参数”以更改方向。以下代码完成了所有这些。这就是你要追求的吗?

M = zeros(100,100);
rowFirst = true; % set to false for "column first"
for i = 1:12:100-12+1
    for j = 1:12:100-12+1
        block = rand(12,12);

        if rowFirst
          M((0:11) + i, (0:11) + j) = block;
        else
          M((0:11) + j, (0:11) + i) = block;
        end

        imagesc(M); axis equal tight xy
        pause(.1)

    end
end

更新2 ,现在“即使是非方形矩阵”(未经测试,深夜):

M = zeros(100, 120);
rowFirst = true;
sz = size(M);
blockSize = 12;
v = 1:blockSize;
nrc = floor(sz / blockSize);
if rowFirst
  nrc = reverse(nrc);
end
for ii = blockSize * (0:nrc(1)-1)
  for jj = blockSize * (0:nrc(2)-1)
    block = rand(blockSize*[1 1]);
    if ~rowFirst
      block = block';
    end if
    M(v + ii, v+jj) = block;
    if rowFirst
      imagesc(M);
    else
      imagesc(M');
    end
    axis equal tight xy
    pause(0.1)
  end
end

最后时间如果您坚持认为外部循环遍历j而内部循环覆盖i,那么在某些情况下j是“更快移动“变量,你可以做到以下几点。

P = 120;
Q = 180;
M = zeros(P, Q); % not a square matrix
rowFirst = true; % a switch you can flip
blockSize = 15;  % size of block
sz = floor(size(M)/blockSize); % number of iterations in j, i
nr = sz(1); nc = sz(2);
vv = 1:blockSize;

for jj = 0: (nc-1)
  for ii = 0: (nr-1) 
    if(rowFirst)
      kk = ii * blockSize;
      ll = jj * blockSize;
    else
      nn = jj * nr + ii;
      ll = mod(nn, nc);
      kk = floor(nn / nc);
      %ll = (nn - kk * nc);
          fprintf(1, 'ii, jj, nn = [%d, %d, %d]: [kk, ll] = %d, %d\n', ii, jj, nn, kk, ll)

      ll = ll * blockSize; kk = kk * blockSize;
     % mod(nn, P);
    end
    M(kk+vv, ll+vv) = rand(blockSize*[1 1]);
    imagesc(M); 
    axis tight equal xy;
    pause(0.1);
 end
end