# 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?

1 vue (au cours des 30 derniers jours)
Makaio le 30 Mar 2023
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
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Cameron le 30 Mar 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
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Plus de réponses (1)

Stephen23 le 30 Mar 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
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by