uhoh, missed two lines on the top.Sorry about that.
the whole code looks like this.


nchars = 4
maxvals = c(2,2,2,2)
tmp = 0:(maxvals[1])
for(i in 2:nchars) {
  tmp <- outer(tmp, 0:(maxvals[i]), FUN="paste", sep=".")
}
states = tmp
stateidx = array(1:length(states), dim=dim(states))
transition <- matrix(data=0, nrow=length(states), ncol=length(states))

findstatedim <- function(x) which(stateidx==x, arr.ind = TRUE)
manhattandistance <- function(x,y) sum(abs(findstatedim(x)-findstatedim(y)))

    for(i in 1:length(states)) {
      for (j in 1:length(states)) {
        if (manhattandistance(i, j)==1) {
          if (sum(findstatedim(i)-findstatedim(j)) < 0) {
            transition[i,j] = "gain"
            if (findstatedim(i)[findstatedim(i)-findstatedim(j) == -1] == 1)
{
              transition[i,j] = "firstgain"
            }
          }
          else {
            transition[i,j] = "loss"
          }
        }
      }
    }
transition



On Thu, May 7, 2009 at 2:54 PM, miraceti <mirac...@gmail.com> wrote:

> Hi, I am still not familiar with vectorization.
> Could you help with making this for loop more efficient?
> The code is trying to make a Q matrix for a multidimensional state space
> with specific conditions.
>
> thanks
> Mira
>
>
> tmp = 0:(maxvals[1])
> for(i in 2:nchars) {
>   tmp <- outer(tmp, 0:(maxvals[i]), FUN="paste", sep=".")
> }
> states = tmp
> stateidx = array(1:length(states), dim=dim(states))
> transition <- matrix(data=0, nrow=length(states), ncol=length(states))
>
> findstatedim <- function(x) which(stateidx==x, arr.ind = TRUE)
> manhattandistance <- function(x,y)
> sum(abs(findstatedim(x)-findstatedim(y)))
>
>     for(i in 1:length(states)) {
>       for (j in 1:length(states)) {
>         if (manhattandistance(i, j)==1) {
>           if (sum(findstatedim(i)-findstatedim(j)) < 0) {
>             transition[i,j] = "gain"
>             if (findstatedim(i)[findstatedim(i)-findstatedim(j) == -1] ==
> 1) {
>               transition[i,j] = "firstgain"
>             }
>           }
>           else {
>             transition[i,j] = "loss"
>           }
>         }
>       }
>     }
> transition
>
>

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to