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 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Cameron
Cameron am 30 Mär. 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

Weitere Antworten (1)

Stephen23
Stephen23 am 30 Mär. 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by