Creating an Array with nested for loops.

If I have an array say A = 1:4, how would I create a new 1 x 7 array with the following elements and structure with a nested for loop? I'm very confused.
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4

1 comentario

Stephen23
Stephen23 el 21 de Sept. de 2016
Editada: Stephen23 el 21 de Sept. de 2016
@Nikko Jeffreys: I edited your question and replaced the example that you just deleted. Please do not delete or edit questions so that they do not make sense. We are not your personal MATLAB help service: we are volunteers here to help everyone who reads this forum. When you edit your question and remove all useful information you make our answers useless for anyone else reading this forum, the exact people we volunteer to help.

Iniciar sesión para comentar.

 Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 19 de Sept. de 2016
Editada: Andrei Bobrov el 19 de Sept. de 2016
A = 1:4;
m = numel(A);
[ii,jj] = ndgrid(1:2*m-1);
out = A(max(abs(ii-m),abs(jj-m))+1);
or
m = numel(A);
s = zeros(2*m-1);
s(m,m) = 1;
out = A(bwdist(s,'chessboard')+1);
or with for..end loop
m = numel(A);
out = zeros(2*m-1);
for jj = 1:m
out(jj:m*2-jj,jj:m*2-jj) = A(m + 1 -jj);
end

Más respuestas (2)

Stephen23
Stephen23 el 19 de Sept. de 2016
Editada: Stephen23 el 19 de Sept. de 2016
Using a for loop:
A = 1:4;
N = numel(A);
B = NaN(2*N-1);
for k = 1:N
B([N+k-1,N-k+1],:) = A(k);
B(:,[N+k-1,N-k+1]) = A(k);
end
KSSV
KSSV el 19 de Sept. de 2016
B = ones(7) ;
B(1,:) = 4 ; B(2,2:end-1) = 3 ;B(3,3:end-2)=2 ;
B(:,1) = 4 ; B(2:end-1,2) = 3 ;B(3:end-2,3)=2 ;
B(:,end) = 4 ;B(2:end-1,end-1) = 3 ;B(3:end-2,end-2)=2 ;
B(end,:) = 4 ;B(end-1,2:end-1)=3 ;B(end-2,3:end-2)=2 ;

1 comentario

KSSV
KSSV el 19 de Sept. de 2016
not a deal..you can put the above in loop..

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Preguntada:

el 19 de Sept. de 2016

Editada:

el 21 de Sept. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by