How to create a matrix of size N×N that has ones in the border and zeros inside?

66 vues (au cours des 30 derniers jours)
Create a matrix of size N×N that has ones in the border and zeros inside.
For example, if N=3 the matrix can be created with
>> A=ones(3,3);
A(2,2)=0
A =
1 1 1
1 0 1
1 1 1
Make this construction depend on N and work for any positive integer N≥2.

Réponse acceptée

KL
KL le 6 Sep 2017
Modifié(e) : KL le 6 Sep 2017
function A = oneZeroMatrix(N)
A = zeros(N);
A([1 end],:)=1;
A(:,[1 end])=1;
end
% and then
N = 5;
A = oneZeroMatrix(N);
  2 commentaires
Carolyn
Carolyn le 26 Nov 2022
Shouldn't it be [1:end] inside the "A" matrix instead of [1 end]?
Walter Roberson
Walter Roberson le 26 Nov 2022
Let us experiment:
N = 5;
A = oneZeroMatrix_original(N)
A = 5×5
1 1 1 1 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 1 1 1 1
A = oneZeroMatrix_modified(N)
A = 5×5
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
function A = oneZeroMatrix_original(N)
A = zeros(N);
A([1 end],:)=1;
A(:,[1 end])=1;
end
function A = oneZeroMatrix_modified(N)
A = zeros(N);
A([1:end],:)=1;
A(:,[1:end])=1;
end

Connectez-vous pour commenter.

Plus de réponses (1)

Stephen23
Stephen23 le 6 Sep 2017
Modifié(e) : Stephen23 le 26 Nov 2022
M = ones(5);
M(2:end-1,2:end-1) = 0
M = 5×5
1 1 1 1 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 1 1 1 1

Catégories

En savoir plus sur Argument Definitions 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