Hi everyone,
How can I extract for example every other element (even or odd) of a matix to form a new matrix?
Hi,
I don’t think that the question is quite specific, but this might help. Given a matrix:
matrix = RandomReal[1, {5, 5}]
We can display it in TableForm
matrix // TableForm

Now we can take all entries which have only odd entries:
matrix[[1 ;; ;; 2, 1 ;; ;; 2]] // TableForm

or only the even ones:
matrix[[2 ;; ;; 2, 2 ;; ;; 2]] // TableForm
![]()
In fact, I can choose any index combination I like:
matrix[[{1, 2, 5}, {2, 4, 5}]] // TableForm

Cheers,
Marco
Thanks Marco
And what if I want to collect the odd elements from the first row and even elements from the second row and again odd ones from the third row and so forth to form a new matrix?
There are many different ways (certainly lots of them are more elegant than this one):
matrix = RandomReal[1, {6, 6}];
DeleteCases[Table[If[EvenQ[i + j], matrix[[i, j]]], {i, 1, 6}, {j, 1, 6}], Null,Infinity] // MatrixForm
Here’s another option:
Table[Reap[Do[If[EvenQ[i + j], Sow[matrix[[i, j]]]], {j, 1, 6}]], {i, 1, 6}][[All, 2, 1]] // MatrixForm
This one might be the nicest of the three:
Pick[matrix, Table[If[EvenQ[i + j], 1, 0], {i, 1, 6}, {j, 1, 6}], 1]
Cheers,
Marco
Thanks a lot!
I was wondering if I want to do the procedure only on even (or odd) rows, what should I add and where?