-2

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.

hhh
  • 2,603
  • 2
  • 19
  • 30

1 Answers1

1

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.

Michael E2
  • 235,386
  • 17
  • 334
  • 747