3
$\begingroup$

Thank you for looking and answering this question. I am trying to create a new matrix from an old one. Meaning, I have a original matrix that's 20x20. I want to keep the first five lines of the matrix, then from line 6-10 I want to take every other line, meaning line 7 and 9 would be deleted, but also column 7 and 9 need to be deleted. Then from line 11-20, I want to take every 3 lines, so the rows and columns need to be deleted accordingly.

$\endgroup$
7
$\begingroup$

I'll use this example matrix:

matrix = Table[i + j, {i, 20}, {j, 0, 19}]

Please take a look at it. You'll notice that the top row has the elements 1-20 and that the leftmost column as has those as well. Now let's create a list of the columns/rows that you want to keep:

keep = Join[Range[5], Range[6, 10, 2], Range[11, 20, 3]]
(* Out: {1, 2, 3, 4, 5, 6, 8, 10, 11, 14, 17, 20} *)

Then:

matrix[[keep, keep]]

This results in the matrix below (visualized with MatrixForm):

Final matrix

$\endgroup$
  • $\begingroup$ After your last edit +1 matrix[[keep, keep]] is very elegant $\endgroup$ – eldo Aug 7 '14 at 17:31
  • $\begingroup$ Ditto. Never seen Part used like that before. +1. $\endgroup$ – seismatica Aug 7 '14 at 20:11
  • 1
    $\begingroup$ @seismatica Have a look at this: (20228) -- Pickett: +1 on a clean answer. :-) $\endgroup$ – Mr.Wizard Aug 8 '14 at 6:01
  • $\begingroup$ @Mr.Wizard Thanks! $\endgroup$ – seismatica Aug 8 '14 at 6:02
  • $\begingroup$ thanks for the ideas, the problem is that the matrix is going to be growing, and I need a systematic way to only take every 10th row, therefore I will have to delete a lot more rows and columns then in this 20x20 example. $\endgroup$ – user2558894 Aug 9 '14 at 6:47
1
$\begingroup$

producing some random data

data = RandomInteger[100, {20, 20}]

If I understood well, you mean

data[[{1, 2, 3, 4, 5, 6, 8, 10, 11, 14, 17, 20}]] // Transpose // 
  Part[#, Range@20~Complement~{7, 9}] & // Transpose
$\endgroup$
1
$\begingroup$

In other cases (few deletions) one could also consider Delete:

m = Partition[Range[400], 20];

del = {{7}, {9}, {12}, {13}, {15}, {16}, {18}, {19}};

m // Delete[del] // Transpose // Delete[del] // Transpose // MatrixForm

enter image description here

$\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.