How to combination between this code A=zeros(8); for i=1:4 for j=1:8-(i+3) A(i,j)=1; end end A and this A=ones(4,8); for i=1:4 for j=1:8-(i) A(i,j)=0; end end A ?

1 view (last 30 days)
How to combination between this code
A=zeros(8);
for i=1:4
for j=1:8-(i+3)
A(i,j)=1;
end
end
A
and this
A=ones(4,8);
for i=1:4
for j=1:8-(i)
A(i,j)=0;
end
end
A
after combination this result
1 1 1 1 0 0 0 0
1 1 1 0 0 0 0 0
1 1 0 0 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 1
0 0 0 0 0 1 1 1
0 0 0 0 1 1 1 1

Answers (2)

Image Analyst
Image Analyst on 5 Mar 2015
Here's the easiest way to create A:
A = [...
1 1 1 1 0 0 0 0
1 1 1 0 0 0 0 0
1 1 0 0 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 1
0 0 0 0 0 1 1 1
0 0 0 0 1 1 1 1];
I mean, why even use a loop at all? It's not needed.

Star Strider
Star Strider on 5 Mar 2015
If you want to do it in MATLAB code rather than manually, you only need one loop and the diag and fliplr functions:
A = zeros(8);
for k1 = 4:7
A = A + diag(ones(1,8-k1),k1);
A = A + diag(ones(1,8-k1),-k1);
end
A = fliplr(A)
produces:
A =
1 1 1 1 0 0 0 0
1 1 1 0 0 0 0 0
1 1 0 0 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 1
0 0 0 0 0 1 1 1
0 0 0 0 1 1 1 1

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!