How can I replace the upper off diagonal(super diagonal) and lower off diagonal(sub diagonal) of a matrix?
20 ビュー (過去 30 日間)
古いコメントを表示
Given a symmetric tridiagonal matrix T generated by
n=5;
p=1;
q=1.7;
r=1;
T=full(gallery('tridiagonal',n,p,q,r));
T=[1.8 1 0 0 0;1 1.8 0 0 0;0 1 1.8 1 0;0 0 1 1.8 1;0 0 0 1 1.8]
How do I change the 1 1 1 1 on both upper and lower off diagonal to 1 0 1 0? What if n is arbitrary, is there any code that fix the off diagonals to a desired vector?
0 件のコメント
回答 (5 件)
the cyclist
2024 年 8 月 13 日
% Arbitrary size
N=5;
% Example input
A = rand(N); % NxN random matrix
disp(A)
% Vector to set as the sub- or superdiagonal
v = rand(N-1,1); % The length of v should be one less than the number of rows/columns in A
% Set the subdiagonal to the values in v
A(sub2ind(size(A), 2:N, 1:(N-1))) = v;
% Set the superdiagonal to the values in v
A(sub2ind(size(A), 1:(N-1), 2:N)) = v;
% Display the updated matrix
disp(A)
0 件のコメント
David Goodmanson
2024 年 8 月 13 日
編集済み: David Goodmanson
2024 年 8 月 13 日
Hello Olawale
m = rand(5,5)
m1 = diag(m,1) % original upper diagonal
a = [2 3 4 5]' % new upper diagonal elements
mnew = m - diag(m1,1) + diag(a,1)
and the lower diagonal works the same way with 1 replaced by -1 everywhere.
1 件のコメント
John D'Errico
2024 年 8 月 13 日
Certainly the preferred solution almost always. Far cleaner. Easy on the eyes, to read, to debug. Code that you can follow is important one day in the future, when you will need to change it.
The only reason why an indexing solution would be preferred is if the matrices were large, AND if the time cost was significant, so you were doing this operation sufficiently often to matter.
Naga
2024 年 8 月 13 日
Hello Olawale,
To modify the off-diagonal elements of the symmetric tridiagonal matrix T to a specified pattern, you can use indexing to directly set these values. Below is a MATLAB code snippet that demonstrates how to change the off-diagonal elements to 1 0 1 0 for the given matrix T.
for i = 1:length(desired_vector)
if i <= n-1
T(i, i+1) = desired_vector(i); % Upper off-diagonal
T(i+1, i) = desired_vector(i); % Lower off-diagonal
end
end
0 件のコメント
参考
カテゴリ
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!