# Findings rows in RREF matrix which contain nothing but a pivot

I am asked to find all rows in a matrix in reduced row echelon form which contain nothing but pivots (pivot is $1$, all other entries are $0$).

For example, in this matrix:

$$\begin{bmatrix} 1 & 1 & 1 & 1 \\ 0 & 1 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} \sim \begin{bmatrix} \color{red}1 & 0 & 0 & 0 \\ 0 & 1 & 1 & 0 \\ 0 & 0 & 0 & \color{red}1 \end{bmatrix}$$ the rows whose pivots are marked in red are such rows.

I wrote the following code:

matrix = {{1, 1, 1, 1}, {0, 1, 1, 0}, {0, 0, 0, 1}}; (* Same example. *)
reduced = RowReduce[matrix]
For[i = 1, i <= Length[reduced], ++i,
row = reduced[[i]];
onlyPivot = False;
Clear[pivot];
For[j = 1, j <= Length[row], ++j,
If[And[row[[j]] != 0, Not[ValueQ[pivot]]],
pivot = row[[j]];
onlyPivot = True,
If[And[row[[j]] != 0, ValueQ[pivot]],
onlyPivot = False
]
];
];
Print[onlyPivot];
];


As you can notice, this is very... C-like (at least it works), and probably very inefficient. Is there a better way to do this in Mathematica? What should I be looking into?

• Hi, welcome to Mathematica.SE, please consider taking the tour so you learn the basics of the site. Once you gain enough reputation by making good questions you will be able to vote up and down both questions and answers. When you see good ones, please vote them up by clicking the grey triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. As you receive help, try to give it too, by answering questions in your area of expertise. Commented Nov 30, 2014 at 10:56
• Can be done with a Cases pattern match. If the reduced matrix is rref then could do In[24]:= Cases[rref, {0 ..., 1, 0 ...}] Out[24]= {{1, 0, 0, 0}, {0, 0, 0, 1}} Commented Nov 30, 2014 at 15:45

## 2 Answers

matrix = {{1, 1, 1, 1}, {0, 1, 1, 0}, {0, 0, 0, 1}};(*Same example.*)
(reduced = RowReduce[matrix]) // MatrixForm


r = MapIndexed[{First[#2], Count[#1, 1]} &, reduced];
r = Insert[r, {"row number", "number of 1 in row"}, 1];
Grid[r, Frame -> All]


Or to make nice report, you can add tag field:

r = MapIndexed[{First[#2], z = Count[#1, 1]; z, If[z == 1, "Yes!", "No"]} &, reduced];
r = Insert[r, {"row number", "number of 1 in row", " result"}, 1];
Grid[r, Frame -> All]


• Thanks a lot! MapIndexed is a great thing! Commented Nov 30, 2014 at 13:05
pcF = Length /@ SparseArray[#]["AdjacencyLists"] &;

pcF@reduced
(* {1, 2, 1} *)

Row[Grid /@ {matrix, reduced, List /@ (pcF@reduced)}, Spacer[10]]


pcF2 = Length[#] == 1 & /@ SparseArray[#]["AdjacencyLists"] &;
pcF2@reduced
(* {True, False, True} *)
Row[Grid /@ {matrix, reduced, List /@ (pcF2@reduced)}, Spacer[10]]