How to create a checkerboard matrix without inbuilt function.

조회 수: 29 (최근 30일)
Riley Smith
Riley Smith 2017년 9월 12일
댓글: Mendi 2020년 9월 6일
I just want to write this matrix, but want to do it using for loops
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
  댓글 수: 8
James Tursa
James Tursa 2017년 9월 12일
Using the sin function for this would be a sin ...
Cedric
Cedric 2017년 11월 28일
편집: Cedric 2017년 11월 28일
I had missed this comment ... ;-)
It's one of the rare cases where using a cos would be a sin too ..
0.5-(-1).^((1:n)+(1:n).')/2
or
a = 1 : n ;
a + a.' == 1

댓글을 달려면 로그인하십시오.

채택된 답변

Joseph Cheng
Joseph Cheng 2017년 9월 12일
There are much easier ways to do this than nested for loops, reshape is readily available. if you must do it with for loops you want to start off with the template
for Rind=1:Nrows
for Cind=1:Ncols
Checkerboard(Rind,Cind) = ___;%what condition of Rind and Cind gives you the checker board pattern.
%start with the first row what makes a 1 appear when Rind==1 and Cind=a number.
%then think of the sigificant difference between Rind==1 and Rind==2.....
end
end

추가 답변 (4개)

ksam K
ksam K 2017년 11월 25일
%Hope this helps you.
function a = checkerboard(n)
a = zeros(n);
for i = 1:n
for j = 1:n
if (i == j)
a (i, j) = 0;
elseif (mod(j, 2) == 0) && (mod(i,2) == 0)
a(i,j) = 0;
elseif (mod(j, 2) == 0) || (mod(i,2) == 0)
a(i,j) = 1;
end
end
end
end

Jan Siegmund
Jan Siegmund 2020년 5월 21일
For an even sized checkerboard:
rows = 6;
cols = 4;
normal = repmat(eye(2,'logical'),[rows/2 cols/2]);
% or
inverted = repmat(~eye(2,'logical'),[rows/2 cols/2]);

Mendi
Mendi 2020년 9월 5일
It is more natural to use modulus on meshgrid:
[iX,iY] = meshgrid(1:8,1:8);
Mask=mod(iX+iY,2);

Bruno Luong
Bruno Luong 2020년 9월 5일
편집: Bruno Luong 2020년 9월 5일
Two more methods
toeplitz(mod(0:7,2))
or for even size
kron(ones(4),[0 1;1 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