This question already has an answer here:
- Does Mathematica have advanced indexing? 6 answers
I love Mathematica, but I find it oddly lacking when it comes to how matrices are handled. Here is an example of code that works but seems like it should be a lot shorter (and minus the loop).
I'm a super-newbie though so maybe one of you smart people has an idea for making this nicer. The point is to take all elements of the matrix that evaluate as True for some criterion (here, being less than 7) and re-assign them to a new value.
testmat = {{-1, 1, -3}, {10, 11, 5}, {15, -2, 7}};
MatrixForm[testmat]
badpos = Position[testmat, _?(# < 7 &)];
{nend, trash} = Dimensions[badpos];
For[i = 1, i <= nend, i++,
selpos = badpos[[i]];
p1 = selpos[[1]];
p2 = selpos[[2]];
testmat[[p1, p2]] = 0;
]
MatrixForm[testmat]

ReplacePart? Using it would eliminate all your code starting at line 4. (I found a reference to it in the help system by searching for "Part", knowing this is the basic function involved in accessing matrix elements.) – whuber Mar 18 at 17:15newmat = testmat /. x_ /; x < 7 -> 0– belisarius Mar 18 at 17:16