4

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?

Eitan T
  • 32,660
  • 14
  • 72
  • 109
Shakedk
  • 420
  • 6
  • 15

2 Answers2

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
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