Why in the heck does this code work?

조회 수: 14 (최근 30일)
Ryan
Ryan 2013년 12월 8일
댓글: Wayne King 2013년 12월 8일
Why in the heck does this code work? It's just a cody problem for a checer board matrix. I figured it out with intuition, trial and error and dumb luck. Lucky too it didn't take too long. I understand the simple use of the colon operator when creating arrays but what happens when using the colon operator with iterations through matrix coordinates? What's going on under the hood hear?
function a = checboard(n)
a=zeros(n);
a(1:2:n,1:2:n)=1;
a(2:2:n,2:2:n)=1;
end

채택된 답변

Wayne King
Wayne King 2013년 12월 8일
편집: Wayne King 2013년 12월 8일
Just look at it one bit at a time. The first time, you take an array of zeros and then set every other row and every other column element to 1.
n = 8;
a = zeros(n);
a(1:2:n,1:2:n) = 1;
Look at a, every other column and every other row are all zeros.
Look at a as an image:
imagesc(a);
Now the next line:
a(2:2:n,2:2:n) = 1;
Adds a one staring in the 2nd column and 2nd row. It then jumps every other column and the same with the rows (putting in a 1).
Now look at a with the bone colormap.
imagesc(a); colormap(bone)
  댓글 수: 2
Ryan
Ryan 2013년 12월 8일
Thanks. I looked at each part breaking it up originally. But I think I see what happens now. Does it do one step of the first iteration then all the steps of the next iteration, like a nested for loop? I thought it was assigning row, column values at the same time. Actually I think I understand the documentation a little more now. Also imagesc() doesn't seem to be working, I'm in the Matlab folder.
Wayne King
Wayne King 2013년 12월 8일
imagesc() is in base MATLAB so that function should work.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by