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 have sparse situation with a lot of zeros, related chat. I want to see only the nonzero things or nonnull things.

Example

Input

hello[ii_, jj_] := If[ii == 1, Return[True], Return[False]]
Table[If[hello[ii, jj], {ii, jj} -> 1], {ii, 1, 5}, {jj, 1, 5}]

Output

{{{1, 1} -> 1, {1, 2} -> 1, {1, 3} -> 1, {1, 4} -> 1, {1, 5} -> 
   1}, {Null, Null, Null, Null, Null}, {Null, Null, Null, Null, 
  Null}, {Null, Null, Null, Null, Null}, {Null, Null, Null, Null, 
  Null}}

Intended Output

{{1, 1} -> 1, {1, 2} -> 1, {1, 3} -> 1, {1, 4} -> 1, {1, 5} -> 1}

where the full form of the intended output could be a 5x5 matrix with 1st row with ones and otherwise zeros.

share|improve this question
    
You may want to study the documentation for SparseArray and ArrayRules. –  David Carraher Nov 9 '13 at 14:42
    
Do you realize that neither your Output nor your intended Output is a SparseArray? –  David Carraher Nov 9 '13 at 15:06
add comment

1 Answer

Perhaps this is what you're thinking of:

SparseArray[{{i_, j_} /; hello[i, j] :> 1}, {5, 5}] // Normal

(* {{1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0,  0}, {0, 0, 0, 0, 0}} *)

Answer to edited question:

SparseArray[{{i_, j_} /; hello[i, j] :> 1}, {5, 5}] // ArrayRules
(* {{1, 4} -> 1, {1, 3} -> 1, {1, 2} -> 1, {1, 5} -> 1, {1, 1} -> 1, {_, _} -> 0} *)

or

SparseArray[{{i_, j_} /; hello[i, j] :> 1}, {5, 5}] // ArrayRules // Most // Sort
(* {{1, 1} -> 1, {1, 2} -> 1, {1, 3} -> 1, {1, 4} -> 1, {1, 5} -> 1} *)

The Sort is optional, depending on whether the output has to be exactly the same as the intended output.

share|improve this answer
    
What do /; and :> mean? –  hhh Nov 9 '13 at 14:31
    
I have a far larger problem Table[If[MiNotJ[ii, jj, mcstable[[All, kk]]] != Null, {ii, jj}], {ii, 1, 31}, {jj, 1, 31}, {kk, 1, 147}] which I tried to formulate in terms of the SparseArray SparseArray[{{ii_, jj_} /; MiNotJ[ii, jj, mcstable[[All, kk]]] -> 1}, {31, 31}] but working. I need to test all combinations with 31x31 matrix. –  hhh Nov 9 '13 at 14:57
    
@hhh Select them and press F1 –  rm -rf Nov 9 '13 at 15:50
1  
@hhh See also the Rules and Patterns section of What the @#%^&*?! do all those funny signs mean? –  Michael E2 Nov 9 '13 at 15:53
    
In your SparseArray code kk is undefined and MiNotJ should return True or False, like hello. (But comments are not for solving side-problems. You can trying pinging me in chat if you need further help.) –  Michael E2 Nov 9 '13 at 15:57
add comment

Your Answer

 
discard

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.