题目
来源于Mathwork上的Cody,Problem 4 - Make a checkerboard matrix.
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]
代码
function a = checkerboard(n)
a=ones(n,n);
for i=1:size(a,1)
for j=1:size(a,2)
if mod(i+j,2)%行列的和为奇数时,该元素置0
a(i,j)=0;
end
end
end
end
其它优秀代码
function a = checkerboard(n)
x=mod(1:n,2);
a = ~xor(x,x');
end