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 views (last 30 days)
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

Accepted Answer

Cameron
Cameron on 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

More Answers (1)

Stephen23
Stephen23 on 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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!