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

onesinborderzerosinside

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.

Best Answer

function A = oneZeroMatrix(N)
A = zeros(N);
A([1 end],:)=1;
A(:,[1 end])=1;
end
% and then
N = 5;
A = oneZeroMatrix(N);