checkerboard matrix (Problem Nr 4 from Cody)

조회 수: 5 (최근 30일)
Hidd_1
Hidd_1 2021년 3월 30일
답변: DGM 2021년 3월 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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by