Given an integer n, make an n-by-n matrix made up of alternating ones and zeros as shown below. The a(1,1) should be 1.
Input n = 5
Output a is [1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]
Code:
clc
m=input('Enter the number:');
x=[1 0];
Y=[];
for i=1:(m*m) Y=[Y x];
end
k=1;
Z=[];
for i=1:m for j=1:m Z(i,j)=Y(k); k=k+1; end
end
If you want to generate the matrix exactly like checkerboard (which will work for both even and odd number , then check the below code)
clc
m=input('Enter the number:');
if(rem(m,2)~=0)
x=[1 0];
Y=[];
for i=1:(m*m) Y=[Y x];
end
k=1;
Z=[];
for i=1:m for j=1:m Z(i,j)=Y(k); k=k+1; end
end
else
x=[1 0];
Y=[];
for i=1:(m*m) Y=[Y x];
end
k=1;
Z=[];
for i=1:m for j=1:m Z(i,j)=Y(k); k=k+1; end
end
for i=1:m for j=1:m if(rem(i,2)==0) if(Z(i,j)==1) Z(i,j)=0; else Z(i,j)=1; end end end
end
end
Generate periodic sequence in MATLAB:
Không có nhận xét nào:
Đăng nhận xét