How can I create a matrix of alternating 1s and 0s for any size matrix?

73 views (last 30 days)
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
  2 Comments
Dipesh  Mudatkar
Dipesh Mudatkar on 18 May 2018
Edited: Dipesh Mudatkar on 18 May 2018
function a = AlternateZeroOnes(n)
a=ones(n);
if rem(n,2)
a(2:2:numel(a))=0;
else
a(n+1,:)=1;
a(:,n+1)=1;
a(2:2:numel(a))=0;
a(n+1,:)=[];
a(:,n+1)=[];
end
end
Stephen23
Stephen23 on 18 May 2018
Edited: Stephen23 on 18 May 2018
@Dipesh Mudatkar: expanding with an extra column is not required, as only adding the extra row makes any difference to the linear indexing. So you could just use this:
a(n+1,:)=1;
a(2:2:numel(a))=0;
a(n+1,:)=[];
To avoid the first resizing and moving of the array in memory you could easily create the array with the correct size in the first place:
function a = AlternateZeroOnes(n)
if rem(n,2)
a = ones(n);
a(2:2:numel(a)) = 0;
else
a = ones(n+1,n);
a(2:2:numel(a)) = 0;
a(n+1,:)=[];
end
end
Unfortunately with this concept there is no way to avoid the second resize and move in memory.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 8 Apr 2015
Edited: Stephen23 on 8 Apr 2015
You could use toeplitz for this:
>> toeplitz(mod(1:n,2))
ans =
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1
  2 Comments
Stephen23
Stephen23 on 21 Apr 2015
Edited: Stephen23 on 30 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

Sign in to comment.

More Answers (1)

James Tursa
James Tursa on 8 Apr 2015
1 - mod(bsxfun(@plus,(1:n)',1:n),2)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!