Home > Net >  Matlab find() function in R
Matlab find() function in R

Time:10-22

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. https://psyarxiv.com/b4jm6/

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. https://de.mathworks.com/help/matlab/ref/find.html

find() from the R package pracma, which only seems to conver find(x): https://www.rdocumentation.org/packages/pracma/versions/1.1.0/topics/find

CodePudding user response:

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

  • Related