Replace the diagonal with NaN in this 5x5 matrix

19 次查看(过去 30 天)
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

采纳的回答

Allen
Allen 2021-3-1
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;

更多回答(1 个)

James Tursa
James Tursa 2021-3-1
You could use linear indexing for the diagonal. E.g., assuming x is square you could add this line to your function:
y(1:size(x,1)+1:end) = nan;

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by