user2543622
user2543622

Reputation: 6766

R vectorizing for loops that run on matrix

Below code assigns a random value between 0 to 1 to each matrix element that is equal to 1. My actual matrix is very large and below code takes a lot of time to run. How can i make it faster. Please note that each cell that is 1 should get a random value between 0 to 1. I dont want all cells to get a same value

#convert black pixels to a random color between 0 to 1

mat1=matrix(c(1,1,0,0.5,1,0.4),nrow=2)
collection=c()
value=0
mat1
mat1==1
for (counter1 in (1:nrow(mat1)))
{
  for (counter2 in (1:ncol(mat1)))
  {
    if(mat1[counter1,counter2]==1){value=runif(1,0,1);mat1[counter1,counter2]=value;collection=c(collection,value)}
  }
}
mat1

Upvotes: 1

Views: 37

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545618

One line is all that’s needed:

mat1[mat1 == 1] = runif(sum(mat1 == 1), 0, 1)

mat1 == 1 selects all elements in the matrix equal to 1. sum(…) gives you the number of these elements, so that runif(…) can generate the desired number of random values.

Finally, by using element assignment (mat1[mat1 == 1] = …), we replace only the elements with value 1 by the newly generated random values.

Upvotes: 2

Related Questions