checkerboard matrix (Problem Nr 4 from Cody)

6 visualizaciones (últimos 30 días)
Hidd_1
Hidd_1 el 30 de Mzo. de 2021
Respondida: DGM el 30 de Mzo. de 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

Respuesta aceptada

DGM
DGM el 30 de Mzo. de 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')

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by