Triangular matrix building with Matlab

78 Views Asked by At

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$

1

There are 1 best solutions below

0
On

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