Asked by Thomas DiMauro
on 8 Apr 2015

I am trying to script that will display a square matrix of alternating 1s and 0s.

ex: 1 0 1 0

0 1 0 1

1 0 1 0

0 1 0 1

I have found that my solution works only for odd values of n, but not even values of n.

Here is what I have so far:

function y=exercise1(n)

%create a square matrix of size n x n

if rem(n,2)== 0

m = zeros(n,n);%displays a matrix of zeros

m(1:2:end,2) = 1 %extracts odd elements from column 2 and makes them a 1

m(2:2:end,1) = 1 %extracts even elements from column 1 and makes them 1

else

mod(n,n)

m = zeros(n,n);%displays a matrix of zero

m(1:2:end) = 1 %extracts all odd elements and makes them a one

end

Answer by Stephen Cobeldick
on 8 Apr 2015

Edited by Stephen Cobeldick
on 8 Apr 2015

Accepted Answer

>> toeplitz(mod(1:n,2))

ans =

1 0 1 0

0 1 0 1

1 0 1 0

0 1 0 1

Stephen Cobeldick
on 21 Apr 2015

And just for completeness...

If the rows~=columns:

>> toeplitz(mod(1:3,2),mod(1:5,2))

ans =

1 0 1 0 1

0 1 0 1 0

1 0 1 0 1

and if the first value should be zero:

>> toeplitz(mod(0:2,2))

ans =

0 1 0

1 0 1

0 1 0

Justin
on 28 Aug 2016

This has helped a lot.

Thankyou.

Sign in to comment.

Answer by James Tursa
on 8 Apr 2015

1 - mod(bsxfun(@plus,(1:n)',1:n),2)

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Dipesh Mudatkar (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/196631-how-can-i-create-a-matrix-of-alternating-1s-and-0s-for-any-size-matrix#comment_569324

## Stephen Cobeldick (view profile)

Direct link to this comment:https://www.mathworks.com/matlabcentral/answers/196631-how-can-i-create-a-matrix-of-alternating-1s-and-0s-for-any-size-matrix#comment_569341

Sign in to comment.