checkerboard matrix (Problem Nr 4 from Cody)

7 views (last 30 days)
Hidd_1
Hidd_1 on 30 Mar 2021
Answered: DGM on 30 Mar 2021
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

Accepted Answer

DGM
DGM on 30 Mar 2021
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')

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!