Skip to main content

list manipulation - Get positions of all non zero matrix elements


I want to find all non zero elements of a table and I want to create a list that contains the name of the table the element was removed from, the position of the element, and the value of the element.


Then to the generated list I would like to apply a replacment rule to the row and the column.



rule = {1 -> "a", 2 -> "b", 3 -> "c"}

{ {tablename, row, col, value} }

For example I have tried


dataTable1 = {{1,0,0}, {0,1,0}, {0,0,-1}} 

Position[Abs[dataTable1], # > 0 &]

but I am unable to get get the position. I would like the final out put to be



 { {"dataTable1", 1,1,1}, {"dataTable1", 2,2,1}, {"dataTable1", 3,3,-1} }

If we apply the replacment.


  { {"dataTable1", 1,1,1}, {"dataTable1", 2,2,1}, {"dataTable1", 3,3,-1} } /. rule 

Then the output should be


 { {"dataTable1", "a","a",1}, {"dataTable1", "b","b",1}, {"dataTable1", "c","c",-1} }

Answer



info[tbl_] := With[{s = SparseArray[tbl]},
ArrayPad[Append @@@ Transpose[{s["NonzeroPositions"], s["NonzeroValues"]}],

{0, {1, 0}}, ToString@Unevaluated@tbl]]

SetAttributes[info, HoldFirst]

result=info[dataTable1]

(* {{"dataTable1", 1, 1, 1}, {"dataTable1", 2, 2, 1}, {"dataTable1", 3, 3, -1}} *)

As to the second part of your query, assume the result from the info function is in a symbol named result, then using your example rule list,


MapAt[(# /. rule) &, result, {All, 2 ;; 3}]


(*
{{"dataTable1", "a", "a", 1}, {"dataTable1", "b", "b", 1},{"dataTable1", "c", "c", -1}}
*)

Comments