Message Boards Message Boards

0
|
4643 Views
|
6 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Extracting specific elements of a matrix

Posted 9 years ago

Hi everyone, How can I extract for example every other element (even or odd) of a matix to form a new matrix?

POSTED BY: fary farfar
6 Replies
Posted 9 years ago

I was wondering if I want to do the procedure only on even (or odd) rows, what should I add and where?

POSTED BY: fary farfar
Posted 9 years ago

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?

POSTED BY: fary farfar

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

POSTED BY: Marco Thiel
Posted 9 years ago

Thanks a lot!

POSTED BY: fary farfar

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

enter image description here

Now we can take all entries which have only odd entries:

matrix[[1 ;; ;; 2, 1 ;; ;; 2]] // TableForm

enter image description here

or only the even ones:

matrix[[2 ;; ;; 2, 2 ;; ;; 2]] // TableForm

enter image description here

In fact, I can choose any index combination I like:

matrix[[{1, 2, 5}, {2, 4, 5}]] // TableForm

enter image description here

Cheers,

Marco

POSTED BY: Marco Thiel
Posted 9 years ago

Thanks Marco

POSTED BY: fary farfar
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract