my question is what is wrong with my code, the results should be in the first picture not the second.

조회 수: 1 (최근 30일)
D=zeros(6);
for row=1:6
for col=1:6
if col>row %upper right corner
D(row,col)=0
else if col==row %diagonal
D(row,col)=0
else if row>col % bottom left corner
if mod(row,2) ==0 && col==1
D(row,1)= row-1
if mod(row,2)==0 && mod(col,2) ==1 && col>=3
D(row,col)= (row-1)*2
if mod(row,2) ==1 && mod(col,2) ==0
D(row,col)= (row-1)*2
end
end
end
end
end
end
end
end

채택된 답변

David Goodmanson
David Goodmanson 2021년 9월 30일
편집: David Goodmanson 2021년 9월 30일
Hi jana,
the problem is that the if statements
if mod(row,2)==0 && mod(col,2) ==1 && col>=3 % (b)
and
if mod(row,2) ==1 && mod(col,2) ==0 % (c)
are contained within
if mod(row,2) ==0 && col==1 % (a)
.......
.......
end
and their conditions conflict with (a) so they never are implemented. If for both (b) and (c) you change 'if' to 'elseif' and then get rid of two suddenly extraneous end statements at the end, it works.
  댓글 수: 2
jana nassereddine
jana nassereddine 2021년 9월 30일
hey, I just solved an hour ago
D=zeros(50);
for row=1:51
for col=1:51
if col>row %upper right corner
D(row,col)=0
else if col==row %diagonal
D(row,col)=0
end
end
if row>col % bottom left corner
if mod(row,2) ==0 && col==1
D(row,1)= row-1
end
if mod(row,2)==0 && mod(col,2) ==1 && col>2
D(row,col)= (row-1)*2
end
if mod(row,2) ==1 && mod(col,2) ==0
D(row,col)= (row-1)*2
end
end
end
end
David Goodmanson
David Goodmanson 2021년 9월 30일
Hi jana, I forgot to mention that there is no need to do the for loops that set the upper right corner to zero, since your preallocation of D made them zero already.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Optimization에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by