3
$\begingroup$

Currently I am trying to delete a randomly-chosen $i^{th}$ row and column from a square $n \times n$ matrix $A$. So far I come up with the following code:

Drop[A, {RandomInteger[{1, 400}]}, {RandomInteger[{1, 400}]}]

The problem with this command is that the random integer for {i} is not the same as the random integer for {j}.

Is there a way of making them consistent, so that I drop the ith row and corresponding column while maintaining the randomness of selecting $i$?

And if the aim was to not delete the row and column entirely but to replace all their elements with, say 0, how would you go about it?

Thank you.

$\endgroup$
2

2 Answers 2

8
$\begingroup$

Perhaps either of these:

Drop[A, {#}, {#}]&@ RandomInteger[{1, Length@A}]
With[{i = RandomInteger[{1, Length@A}]}, Drop[A, {i}, {i}]]
$\endgroup$
1
  • 2
    $\begingroup$ Answer to the changed question: ...ReplacePart[mat, {_, i} | {i, _} -> SetPrecision[0, Precision@mat]].. $\endgroup$
    – Michael E2
    Jan 14, 2021 at 22:58
3
$\begingroup$
A = Array[a, {7, 7}];

You can also use BlockRandom:

SeedRandom[123]
Drop[A, {BlockRandom[RandomInteger[{1, 7}]]}, {RandomInteger[{1, 7}]}] // MatrixForm

enter image description here

Alternatively,

SeedRandom[123]
Drop[A, {ri = RandomInteger[{1, 7}]}, {ri}] // MatrixForm

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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