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
  • 3
    $\begingroup$ Related: mathematica.meta.stackexchange.com/questions/1808/… $\endgroup$
    – Michael E2
    Commented Jan 14, 2021 at 22:55
  • $\begingroup$ I edited your question title to better reflect the (final?) end goal of your question. It is better for future users to keep such things in order when you’re asking questions. $\endgroup$ Commented Jan 15, 2021 at 1:51

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
    Commented 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 you have read our privacy policy.

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