I have a matrix of 0-1. What I would like to do is to loop into this matrix and search for the 1. Each time a 1 has been found, to simply jump or pass that row, in order to only record 1 value per row.
What I am trying to know if the first episode of the sequence is a 1. I was thinking there might be a solution with
break
But I am unsure how to use it properly.
So this is my first matrix
SoloNight = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0, 0), .Dim = 10:11)
This is my empty matrix - to record the 1.
matSolo = matrix(0, nrow = nrow(SoloNight), ncol = ncol(SoloNight) )
This is my attempt to loop
for(i in 1:nrow(matSolo)){
for(j in 1:ncol(matSolo)){
if(SoloNight[i,j] == 1) break
{matSolo [i,j] <- 1}
}
}
How can I break after finding the value 1 for each rows ?
Any suggestion how I could do that ?
(Expected matrix)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,] 0 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 0 1 0 0 0 0 0 0 0
[9,] 0 1 0 0 0 0 0 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 0 0
You seem to be fond of
for
loops and those seem like a natural choice here. Just change your code to this:However, this will be quite slow for big matrices. Fortunately, it's easy to translate to Rcpp: