MATLAB: Replace the diagonal with NaN in this 5×5 matrix

indexingMATLABmatlab codermatrix manipulation

a=[1 0 0 0 0;0 1 0 0 0;0 0 1 0 0;0 0 0 1 0;0 0 0 0 1]
function y_diagonal =replace_NaN(x)
y=x;
end

Best Answer

Another approach to this if you know that your original matrix will always be a square matrix. You can use the following:
a(eye(size(a))==1) = nan;