R source code explanation.

  • Thread starter user366312
  • Start date

user366312

Gold Member
62
2
Summary
Kindly explain the highlighted lines.
R code:
#==================================================================
# Build the transition matrix for random walk on n-cycle
#------------------------------------------------------------------
n <- 25  # we are creating (nXn) transition matrix
r1 <- c(0, 1/2, rep(0,n-3), 1/2) # create same values 22 times...
tmat <- matrix(0, nrow=n, ncol=n) # create a 0-matrix
tmat[1,] <- r1 # inject values in 'r1' into 'tmat' along the 1st row

for (i in 1:(n-1))
{
    tmat[26-i,] <- r1[1 + (i:(n+i-1)) %% n] # ??? mod operator
}
#=================================================================
What are being done in line#11?

How are elements being selected using mod operator?
 

FactChecker

Science Advisor
Gold Member
2018 Award
4,719
1,613
It really helps to print results and intermediate calculations.
I ran it with this code right after the calculation of r1:
Code:
print("r1")
print( r1 )
And this at the bottom of the loop:
R print code at bottom of loop:
print("1 + (i:(n+i-1)) %% n")
print(1 + (i:(n+i-1)) %% n)
print("26-i")
print(26-i)
print("tmat")
print(tmat[26-i,])
The beginning of the print results are:
Start of print results:
[1] "r1"
 [1] 0.0 0.5 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.5
[1] "1 + (i:(n+i-1)) %% n"
 [1]  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25  1
[1] "26-i"
[1] 25
[1] "tmat"
 [1] 0.5 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.5 0.0
[1] "1 + (i:(n+i-1)) %% n"
 [1]  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25  1  2
[1] "26-i"
[1] 24
[1] "tmat"
 [1] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.5 0.0 0.5
 

Want to reply to this thread?

"R source code explanation." You must log in or register to reply here.

Physics Forums Values

We Value Quality
• Topics based on mainstream science
• Proper English grammar and spelling
We Value Civility
• Positive and compassionate attitudes
• Patience while debating
We Value Productivity
• Disciplined to remain on-topic
• Recognition of own weaknesses
• Solo and co-op problem solving
Top