Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I am very new to Mathematica (first time!) and I'm already having troubles with arrays. I basically have a 4D tensor, that is a matrix (call it M) which has for each entry another matrix. I want to select the elements of the nested matrices that are bigger than zero, but Select[M, # > 0 &] doesn't work. I suspect it is because I do not respect the dimensions. I am kind of lost. Thanks in advance

share|improve this question
Can you post M here? –  J. M. May 15 '13 at 14:20
Do you want the result as a simple list or something more structured (nested lists) ? –  andre May 15 '13 at 14:25
@J.M., i cannot post the whole thing because each entry is an integral of two function multiplied together. –  user24273 May 15 '13 at 14:37
@andre, i need to make a matrix out of it –  user24273 May 15 '13 at 14:38
here is how it looks like, where the s and s' are the functions that i integrate. ex = Array[s[#1, #2] s'[#3, #4] &, {4, 4, 4, 4}, {1, 0, 1, 0}] –  user24273 May 15 '13 at 14:41

2 Answers 2

up vote 3 down vote accepted
m = RandomInteger[{1, 42}, {3, 3, 3, 3}];

Cases will extract every element equal to 42 here. (There won't always be any for the random nature.)

Cases[m, i_Integer /; i == 42, Infinity]

With Position you can identify where these elements are.

Position[m, i_Integer /; i == 42, Infinity]

Select selects sublists (row of matrices in this case) with some property, whether for example they containt a matrix with 42.

Select[m, MemberQ[Flatten[#], 42] &]
share|improve this answer
You can replace levelspec Infinity with {4} for the nature of your input. –  BoLe May 15 '13 at 14:33
"(There won't always be any for the random nature.)" - for reproducibility, look up SeedRandom[]. –  J. M. May 15 '13 at 14:37
@J.M. BlockRandom[...] for example, I know that. Chances are with that many elements there will be at least one 42. :) –  BoLe May 15 '13 at 14:42
yes!!! It worked! I think its just because its the first time i use this program and i dont know how and where to use the right functions. Thanks a lot guys. –  user24273 May 15 '13 at 14:48
@user, if you're searching for a specific number, then this also works: Cases[m, 42, Infinity] (similarly with Position[]). –  J. M. May 15 '13 at 15:13

If you goal is a matrix of the origial dimensions retaining only the selectred values you could do something like this:

  Map[ If[# > 0, #, Null] & , m , {-1}]
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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