如何尽快生成自定义的棋盘格矩阵? [英] How to generate a customized checker board matrix as fast as possible?
问题描述
我需要一个函数来创建具有M
行和N
列的P*Q
矩形的棋盘格矩阵.我从此处修改了第三种解决方案,以获得
I need a function that creates a checker board matrix with M
rows and N
columns of P*Q
rectangles. I modified the third solution from here to get that:
function [I] = mycheckerboard(M, N, P, Q)
nr = M*P;
nc = N*Q;
i = floor(mod((0:(nc-1))/Q, 2));
j = floor(mod((0:(nr-1))/P, 2))';
r = repmat(i, [nr 1]);
c = repmat(j, [1 nc]);
I = xor(r, c);
它没有问题:
I=mycheckerboard(2, 3, 4, 3)
I =
0 0 0 1 1 1 0 0 0
0 0 0 1 1 1 0 0 0
0 0 0 1 1 1 0 0 0
0 0 0 1 1 1 0 0 0
1 1 1 0 0 0 1 1 1
1 1 1 0 0 0 1 1 1
1 1 1 0 0 0 1 1 1
1 1 1 0 0 0 1 1 1
但是它不够快,因为在一次运行中有很多此函数的调用.有没有更快的方法来获得结果?如何删除floor
函数的浮点除法和/或调用?
But it's not fast enough since there are lots of calls of this function in a single run. Is there a faster way to get the result? How can I remove floating point divisions and/or calls of the floor
function?
推荐答案
对于小型矩阵,您的代码相当快,但是随着尺寸变大,您的代码将变得越来越少.这是使用 bsxfun
和
Your code is fairly fast for small matrices, but becomes less so as the dimensions get larger. Here's a one-liner using bsxfun
and imresize
(requires Image Processing toolbox that most have):
m = 2;
n = 3;
p = 4;
q = 3;
I = imresize(bsxfun(@xor, mod(1:m, 2).', mod(1:n, 2)), [p*m q*n], 'nearest')
或者,受@AndrasDeak使用 kron
的启发,使用R2015b可以更快:
Or, inspired by @AndrasDeak's use of kron
, this is faster with R2015b:
I = kron(bsxfun(@xor, mod(1:m, 2).', mod(1:n, 2)), ones(p, q))
要稍微提高速度,可以利用问题的结构来简化kron
的基础代码:
For a small bit more speed, the underlying code for kron
can be simplified by taking advantage of the structure of the problem:
A = bsxfun(@xor, mod(1:m, 2).', mod(1:n, 2));
A = permute(A, [3 1 4 2]);
B = ones(q, 1, p);
I = reshape(bsxfun(@times, A, B), [m*n p*q]);
或作为一(长)行:
I = reshape(bsxfun(@times, permute(bsxfun(@xor, mod(1:m, 2).', mod(1:n, 2)), [3 1 4 2]), ones(q, 1, p)), [m*n p*q]);
这篇关于如何尽快生成自定义的棋盘格矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!