Modify off diagonal elements of Matrix without looping

50 ビュー (過去 30 日間)
Chet Sharma
Chet Sharma 2022 年 8 月 17 日
コメント済み: Chet Sharma 2022 年 8 月 17 日
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!

採用された回答

James Tursa
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
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
A = 4×4
10.0000 0.8772 0.1202 0.5331 0.9790 10.0000 0.6722 0.3879 0.1196 0.8373 10.0000 0.2409 0.2357 0.9320 0.4094 10.0000
  3 件のコメント
Chet Sharma
Chet Sharma 2022 年 8 月 17 日
Found a way without the loop....but gosh it's not pretty:
My original matrix is 5x5.
So I create two idx matrices - upper and lower triangular. Then I replace the off-diagonal elements of the original A with the intended constant (skalar). If there's something better than this, I'll take it.....else this is it for now (found it on one of the QA's on the forum).
idx1 = tril(ones(5,5), -1);
idx2 = triu(ones(5,5), 1);
A(idx1==1) = skalar;
A(idx2== 1) = skalar;

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by