How to use diag() once and change values after certain element?

1 view (last 30 days)
For example:
for i = 1:3
matrix(i,i) = diag(2);
matrix(i,i+1) = diag(1);
matrix(i+1,i) = diag(-1);
end
matrix(4,4) = 2;
This outputs
2 1 0 0
-1 2 1 0
0 -1 2 1
0 0 -1 2
So a simpler way of doing the above, use diag() to give a n x n matrix (n being something you choose to be), where the 0th diagonal has 2s, the 1st diagonal has 1s and the -1st diagonal has -1s
For the latter half of my question.
Can you tell where diag() to stop at ?
Basically do diag(2,0) until cell (2,2) and then after that do diag(1,0) for the same matrix. So end result is:
2 0 0 0
0 2 0 0
0 0 1 0
0 0 0 1

Accepted Answer

the cyclist
the cyclist on 24 Feb 2020
Edited: the cyclist on 24 Feb 2020
A simple way to construct the exact matrix in your first part is
matrix = 2*eye(4) + diag([-1 -1 -1],-1) + diag([1 1 1],1)
How you want to generalize this will depend on the specifics of your problem.
I think the blkdiag command will be helpful for the second part.

More Answers (0)

Categories

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

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!