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

  • $\begingroup$ Can you post M here? $\endgroup$ – J. M. will be back soon May 15 '13 at 14:20
  • $\begingroup$ Do you want the result as a simple list or something more structured (nested lists) ? $\endgroup$ – andre314 May 15 '13 at 14:25
  • $\begingroup$ @J.M., i cannot post the whole thing because each entry is an integral of two function multiplied together. $\endgroup$ – user24273 May 15 '13 at 14:37
  • $\begingroup$ @andre, i need to make a matrix out of it $\endgroup$ – user24273 May 15 '13 at 14:38
  • 1
    $\begingroup$ 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}] $\endgroup$ – user24273 May 15 '13 at 14:41
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] &]
  • $\begingroup$ You can replace levelspec Infinity with {4} for the nature of your input. $\endgroup$ – BoLe May 15 '13 at 14:33
  • 1
    $\begingroup$ "(There won't always be any for the random nature.)" - for reproducibility, look up SeedRandom[]. $\endgroup$ – J. M. will be back soon May 15 '13 at 14:37
  • $\begingroup$ @J.M. BlockRandom[...] for example, I know that. Chances are with that many elements there will be at least one 42. :) $\endgroup$ – BoLe May 15 '13 at 14:42
  • $\begingroup$ 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. $\endgroup$ – user24273 May 15 '13 at 14:48
  • 1
    $\begingroup$ @user, if you're searching for a specific number, then this also works: Cases[m, 42, Infinity] (similarly with Position[]). $\endgroup$ – J. M. will be back soon 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}]

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.