Modify off diagonal elements of Matrix without looping
42 次查看(过去 30 天)
显示 更早的评论
Hello
I have a MXM matrix. Is there a way to set off diagonal elements to a specified value (.e.g. I want all off-diagonal elements to be some constant "k'), without looping through the matrix? I know there is a function "diag"....was hoping to find something that does the opposite....not sucessful so far.
Thanks!
0 个评论
采纳的回答
James Tursa
2022-8-17
You could use logical indexing to get at the off-diagonal elements. E.g.,
A(~eye(size(A))) = skalar;
更多回答(1 个)
Bruno Luong
2022-8-17
M = 4;
A = rand(M);
A(1:size(A,1)+1:end) = 10, % This is how you change the diagonal of A using linear indexing
3 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!