checkerboard matrix (Problem Nr 4 from Cody)

4 次查看(过去 30 天)
I found this problem on Cody:
Given an integer n, make an n-by-n matrix made up of alternating ones and zeros as shown below. The a(1,1) should be 1.
Example:
Input n = 5
Output a is [1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1]
My solution seems logical but it doesn't work! can someone help me figure out what's messing.
Here is my solution:
function a = checkerboard(n)
x = ones(n,n)
k = 0;
for i =1:n
for j = 1:n
if rem(k, 2) == 0
x(i,j) = 0;
k = k+1;
end
end
end
a = x;
end

采纳的回答

DGM
DGM 2021-3-30
I can see what you're going for, but you've got a couple issues.
The reason that you're not getting any pattern out is that the k=k+1 increment happens inside the conditional, where it should be happening in every iteration of the inner loop. That said, there's still a problem with using k like this. In this context, k is a linear index, so this solution will only produce a checkerboard if n is odd. otherwise, it'll produce stripes. The way you would fix this is to consider both i and j:
x = ones(n,n);
k = 0;
for i =1:n
for j = 1:n
if xor(rem(i, 2) == 1, rem(j, 2) == 1)
x(i,j) = 0;
end
end
end
a = x;
That said, you should start to see how xor and checkerboards go hand in hand. Ideally, you shouldn't even need any loops.
% assuming nxn square output
n=5;
x=mod(1:n,2);
a=bsxfun(@xor,x,~x')
or
% generalized mxn output
m=4;
n=5;
x=mod(1:n,2);
y=mod(1:m,2);
a=bsxfun(@xor,x,~y')

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by