A
A
Alexey Pavlov2018-04-22 14:53:12
R
Alexey Pavlov, 2018-04-22 14:53:12

So what is the logic behind this construction in R?

I want to display the matrix as a 3D topography (using persp(matrix, expand=value)) and as a wave (I'm having trouble with data types, so I'm practicing). Here is my code:

m <- matrix(0, 10, 10)
st <- 1
fi <- 10
s <- 1
f <- 10
n <- st:fi
l <- s:f

for (j in 1:10) {
  for (i in n) {
    m[i] <- l[i]
  }
  s <- s + 1
  f <- f + 1
  st <- st + 10
  fi <- fi + 10
}
m <- matrix(m, 10, 10)

where the value of element 2 will be equal to the value of 11 (second row), the value of element 3 will be 12 and 21 (second and third rows, respectively), and so on. But I get this as an output (still without converting to a matrix):
[,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    0    0    0    0    0
 [2,]    2    0    0    0    0    0
 [3,]    3    0    0    0    0    0
 [4,]    4    0    0    0    0    0
 [5,]    5    0    0    0    0    0
 [6,]    6    0    0    0    0    0
 [7,]    7    0    0    0    0    0
 [8,]    8    0    0    0    0    0
 [9,]    9    0    0    0    0    0
[10,]   10    0    0    0    0    0
      [,7] [,8] [,9] [,10]
 [1,]    0    0    0     0
 [2,]    0    0    0     0
 [3,]    0    0    0     0
 [4,]    0    0    0     0
 [5,]    0    0    0     0
 [6,]    0    0    0     0
 [7,]    0    0    0     0
 [8,]    0    0    0     0
 [9,]    0    0    0     0
[10,]    0    0    0     0

So. Am I violating my logic or does the language have its own?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Potanin, 2018-04-26
@potan

The outer loop does not change l, which is used in the inner one. And the inner one does not use j, and the same elements of m are overwritten every time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question