Bringing elements to the lower triangular part of the matrix

I am creating a diagonal matrix in MATLAB using eye(3) . How can I assign the number "2" only to elements under the main diagonal?

+4
source share
2 answers

The tril has an additional argument that controls that the bottom triangle is exactly used.

 A = eye(3) + 2*tril(ones(3), -1); 
+5
source

If you are interested in assigning elements to an existing matrix, you can use tril same way as Shai's answers and combine this with logical indexing. For instance:

 A = eye(3); idx = tril(true(size(A)), -1); % # Lower triangular half A(idx) = 2 

What should give the desired result:

 A = 1 0 0 2 1 0 2 2 1 

If you are at the stage of creating such a matrix, then you should generate it, as Shay suggests.

+3
source

All Articles