Matlab Find() Function in R

Matlab Find() Function in R

I am trying to convert some Matlab code into R. The code looks something like this:

u= [.4 .5 .1;
    .2 .4 .4;
    .4 .1 .5]
z= find(cumsum(u)>= rand,1)

OUTPUT: e.g. z = 3

The mathematical background is described like this (from a math tut. script):

We make a vector containing the cumulative sum of the columns (which we know sum to one), generate a random number (0-1),and then use the find function to take the first number in the cumulative sum vector that is >= the random number. For example if our D vector is [.5 .5] 50% of the time the element of the vector corresponding to the state one will be >= to the random number.

I have tried to use find() from the pracma package(docu. link below), but I don't know how to get it working. I get either "dims[product...] do not match the length of object" or mostly just "is.character(what) is not TRUE"...

Matlab function:

k = find(x,n) 

returns the first n indices corresponding to the nonzero elements in X.

find() from the R package pracma, which only seems to conver find(x):

5

1 Answer

Solved by @Rui Barradas: which(cumsum(u)>= runif(1))[1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.