I'm creating a diagonal matrix in MATLAB using eye(3)
. How can I assign the number "2" only to the elements under the main diagonal?
Asked
Active
Viewed 3,546 times
2 Answers
5
The command tril
has an extra argument that controls which lower triangular exactly to use.
A = eye(3) + 2*tril(ones(3), -1);

Shai
- 111,146
- 38
- 238
- 371
-
I removed it because it completely falls short when compared to yours. – Eitan T Dec 25 '12 at 11:52
-
@EitanT "completely" is a very strong word. Thanks for the support. – Shai Dec 25 '12 at 12:01
-
1Hmm... okay then. I've posted a different approach, depending on the OP's desire. – Eitan T Dec 25 '12 at 12:18
3
If you're interested in assigning elements into an already existent matrix, you can use tril
in similar fashion to Shai's answer and combine it with logical indexing. For example:
A = eye(3);
idx = tril(true(size(A)), -1); % # Lower triangular half
A(idx) = 2
Which should yield the desired result:
A =
1 0 0
2 1 0
2 2 1
If you're at the stage of creating such a matrix, then you should generate it like Shai suggests.

Eitan T
- 32,660
- 14
- 72
- 109
-
I copied and paste your code: A = eye(3); idx = tril(true(size(A), -1)); A(idx) = 2 But I still get the identity matrix. What do i do wrong? – Shakedk Dec 25 '12 at 13:38
-
@user1928113 sorry, I forgot to close the parentheses after `size(A)`, and you misplaced them. Please try the fixed answer. – Eitan T Dec 25 '12 at 13:45