0
$\begingroup$

I am completely new to Mathematics. I am doing an exercise which requires me to use Table to make a $10 \times 10$ matrix with numbers $1,2,...,10$ on the diagonal and $1$ in the upper diagonal entries and with $0$ in the lower diagonal matrix.

I have been able to generate the diagonal command along with the upper diagonal command (using If) but that yields $1$ in the lower diagonals also.

Can anybody help me with this code?

$\endgroup$
  • $\begingroup$ Show us the code please. $\endgroup$ – Kuba Apr 25 '18 at 12:22
  • 1
    $\begingroup$ Certainly, nested Ifs or a Which can help here... $\endgroup$ – Henrik Schumacher Apr 25 '18 at 12:44
3
$\begingroup$

As Henrik Schumacher points out in a comment to the question, Which, which can be considered a multi-test version of If, can be used to solve your problem. Like so.

m = Table[Which[i == j, i, i < j, 1, True, 0], {i, 10}, {j, 10}];
m // MatrixForm

matrix

You could also use nested If expressions.

m = Table[If[i == j, i, If[i < j, 1, 0]], {i, 10}, {j, 10}];
$\endgroup$
3
$\begingroup$

One using Switch and another using nested If:

m1 = Table[
   Switch[Positive[i - j], True, 0, False, 1; i], {i, 1, 10}, {j, 1, 
    10}];
m2 = Table[
   If[i - j == 0, i, If[i - j > 0, 0, 1]], {i, 1, 10}, {j, 1, 10}];
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.