creating a diagonalmatrix with diag and add a value to it

14 views (last 30 days)
hi,
I'm trying to create a diagonal matrix, with two minor diagonals and one major diagonal. I already created the two minor, but I don't know how to create the main one.
Code:
%diagonalmatrix
D = diag((-1)*k_i,-1) + diag(k_i+k_(i+1)) + diag((-1)*k_i, 1);
diag((-1)*k_i,-1) and diag((-1)*k_i, 1) already work.
How to change diag(k_i+k_(i+1)) ?
Must I create a new matrix with the addition already included for the major diagonal? How to?
Thanks!
I included the concept in the attachment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 30 Apr 2020
Try this. It shows an example with symbolic variables to show that it creates the correct matrix. You can try it with k as a numeric vector
k = sym('k', [1, 8]);
A = diag(k(2:end-1),1) + diag(k(2:end-1),-1) + diag(k(1:end-1)+k(2:end));
Result
>> A
A =
[ k1 + k2, k2, 0, 0, 0, 0, 0]
[ k2, k2 + k3, k3, 0, 0, 0, 0]
[ 0, k3, k3 + k4, k4, 0, 0, 0]
[ 0, 0, k4, k4 + k5, k5, 0, 0]
[ 0, 0, 0, k5, k5 + k6, k6, 0]
[ 0, 0, 0, 0, k6, k6 + k7, k7]
[ 0, 0, 0, 0, 0, k7, k7 + k8]

More Answers (0)

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!