Triangular Matrix Building with Matlab

Triangular Matrix Building with Matlab
$\begingroup$

Need to fill a triangular matrix on MATLAB with the ndgrid command without using loops.

$\mathbf{Example:}$ To fill a square matrix $a_{ij} = i+2j$, for $i,j = 1..10$, the code would be :

[I,J] = ndgrid(1:10,1:10); A = I+2.*J;

But I don't know how to do so if my matrix is triangular. Say, the matrix defined by :

$a_{ij} = i+2j \quad$, if $i \le j$ and

$a_{ij} = 0 \quad\quad\quad$, if $i > j$

$\endgroup$
2

1 Answer

$\begingroup$

Try [I,J] = ndgrid(1:10,1:10); A = I+2.*J; A(I > J) = 0;

The last line creates a boolean mask which is true for the indices where $i > j$, and then zeroes out those entries of $A$.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.