Borrar filtros
Borrar filtros

How can I create a matrix of size nxn (user input) where all outside numbers are 1, incrementally decreasing by 1 each layer the matrix goes in?

3 visualizaciones (últimos 30 días)
I am trying to write a code that creates something like this for a 5x5 matrix:
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
I currently have this:
rows = input('Input the amount of rows: ');
cols = input('Input the amount of columns: ');
A = [];
for r = 1:rows
for c = 1:cols
for n = 1: rows
if r == n || r == rows-n+1 || c == n || c == cols-n+1
A(r,c) = n;
fprintf('%d ', A(r,c))
end
end
end
fprintf('\n')
end

Respuesta aceptada

Cameron
Cameron el 30 de Mzo. de 2023
n = 5;
mymat = zeros(n);
endVal = n;
startVal = 1;
for a = 1:ceil(n/2)
indx = startVal:endVal;
mymat(indx,indx) = a;
startVal = startVal + 1;
endVal = endVal - 1;
end
disp(mymat)
1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1

Más respuestas (1)

Stephen23
Stephen23 el 30 de Mzo. de 2023
N = 5;
V = min(1:N,N:-1:1);
M = min(V,V.')
M = 5×5
1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by