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 ビュー (過去 30 日間)
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

採用された回答

Cameron
Cameron 2023 年 3 月 30 日
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

その他の回答 (1 件)

Stephen23
Stephen23 2023 年 3 月 30 日
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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by