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 ?

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

Respuestas (2)

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.
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

Categorías

Etiquetas

Preguntada:

el 5 de Mzo. de 2015

Respondida:

el 5 de Mzo. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by