Trying to make a 6x6 checkerboard matrix using for loops and no if statements. trying to get my code down to 7 lines instead of 8.

조회 수: 13 (최근 30일)
Trying to get the bolded code consolodated into 7 lines instead of 8 in order to make a 6x6 checkerboard matrix. I feel like somehow i can nest together all three for loops and only have one line for A()=a
n=6;
a=1;
A=zeros(n,n);
for i=1:2:n-1 %rows 1,3,5
for j=1:2:n %columns 1,3,5
A(i,j)=a;
end
for k=2:2:n %columns 2,4,6
A(i+1,k)=a;
end
end
display(A)

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 9월 29일
편집: Ameer Hamza 2020년 9월 30일
You can create it like this
n=6;
a=1;
A = zeros(n);
for i = 2:2:n
A = A + circshift(eye(n), i);
end
Result
>> A
A =
1 0 1 0 1 0
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
Within only 7 lines with thre for loops:
n=6;
a=1;
A=zeros(n,n);
for i=1:n % all rows
for j=1:2:n %columns 1,3,5
for k=2:2:n %columns 2,4,6
A(i, (mod(i,2)==1)*j+(mod(i,2)==0)*k) = a;
end
end
end
disp(A)
  댓글 수: 2
Mary Jean Savitsky
Mary Jean Savitsky 2020년 9월 29일
its for an assignment that asks for exactly 7 lines including 3 "for" and 3 "end" statements. So I believe there has to be a way to combine both A()=a statements :/ very interesting to see different ways I can make this matrix though, Thank you!
Ameer Hamza
Ameer Hamza 2020년 9월 30일
Check the updated answer. It shows a weird way to create this matrix with 3 "for", 3 "end" and only one line of code.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by