# How to extract a row name that meets a column name criterion in a matrix

 m={{"","N1","N2","N3","N4","N5","N6","N7","N8","N9","N10","N11","N12","N13","N14","N15","N16","N17","N18","N19","N20","N21","N22","N23","N24","N25","N26","N27","N28","N29","N30","N31","N32","N33","N34","N35","N36","N37","N38","N39","N40","N41","N42","N43"},{"N1",0,0,0,1,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0},{"N2",0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}
MatrixForm[m]


For example, Column N5 has a 1 in rows N1 and N2. I would like to have a list printed that shows by each Column name the list of row names that contain a 1. So, column N5 has a 1 in rows {N1, N2} and column N1 has a 1 only in row {N1}, and so forth

• Have a look for the built-in function Position. Apr 4 '18 at 16:31

two ways i can think of with your current m:

g[{0, 0}] = {};
g[{1, 0}] = {"N1"};
g[{0, 1}] = {"N2"};
g[{1, 1}] = {"N1", "N2"};

Map[First@# -> g@Rest@# &, Rest@Thread[m]] // AbsoluteTiming

(* {0.000065641, {"N1" -> {}, "N2" -> {}, "N3" -> {}, "N4" -> {"N1"},
"N5" -> {"N1", "N2"}, "N6" -> {"N1"}, "N7" -> {"N1"},
"N8" -> {"N1"}, "N9" -> {"N1"}, "N10" -> {}, "N11" -> {},
"N12" -> {}, "N13" -> {}, "N14" -> {}, "N15" -> {}, "N16" -> {},
"N17" -> {}, "N18" -> {}, "N19" -> {}, "N20" -> {}, "N21" -> {},
"N22" -> {}, "N23" -> {}, "N24" -> {}, "N25" -> {}, "N26" -> {},
"N27" -> {}, "N28" -> {}, "N29" -> {}, "N30" -> {}, "N31" -> {},
"N32" -> {}, "N33" -> {}, "N34" -> {}, "N35" -> {}, "N36" -> {},
"N37" -> {}, "N38" -> {}, "N39" -> {}, "N40" -> {}, "N41" -> {},
"N42" -> {}, "N43" -> {}}} *)


or using Replace

 Replace[Rest@*Thread@m, {{x_, 1, 0} :> x -> {"N1"},
{x_, 0, 1} :> x -> {"N2"}, {x_, 1, 1} :> x -> {"N1", "N2"}, {x_, __} :> x -> {}}, {1}]


You could do it this way:

rowtitles = m[[2 ;;, 1]];
coltitles = m[[1, 2 ;;]];
A = DeveloperToPackedArray[m[[2 ;;, 2 ;;]]];
{col, title} \[Function] title -> Extract[rowtitles, Position[col, 1]],
{
Transpose[A],
coltitles
}
]


{"N1" -> {}, "N2" -> {}, "N3" -> {}, "N4" -> {"N1"}, "N5" -> {"N1", "N2"}, "N6" -> {"N1"}, "N7" -> {"N1"}, "N8" -> {"N1"}, "N9" -> {"N1"}, "N10" -> {}, "N11" -> {}, "N12" -> {}, "N13" -> {}, "N14" -> {}, "N15" -> {}, "N16" -> {}, "N17" -> {}, "N18" -> {}, "N19" -> {}, "N20" -> {}, "N21" -> {}, "N22" -> {}, "N23" -> {}, "N24" -> {}, "N25" -> {}, "N26" -> {}, "N27" -> {}, "N28" -> {}, "N29" -> {}, "N30" -> {}, "N31" -> {}, "N32" -> {}, "N33" -> {}, "N34" -> {}, "N35" -> {}, "N36" -> {}, "N37" -> {}, "N38" -> {}, "N39" -> {}, "N40" -> {}, "N41" -> {}, "N42" -> {}, "N43" -> {}}

Moreover, I would strongly discourage to store column and row titles within the data matrix since this disables packing of arrays. For instance, compare

ByteCount[m]

ByteCount[A]
`

4160

816

• very clever and helpful ... thank you
– PRG
Apr 5 '18 at 11:30
• You're welcome! Apr 5 '18 at 11:51