0

Advertisement

I'd like to populate a matrix using information from two other matrices

I have managed to do this with a given dataset, but I need to integrate this within a larger script, and the size of the two matrices I'm using to populate the larger matrix may differ each time.

Example data:

```
days = 150
block <- matrix(c(50,120,150), nrow=3, ncol=1)
[,1]
[1,] 50
[2,] 120
[3,] 150
e1 <- matrix(c(0.1,0.5,0.7), nrow=3, ncol=1)
[,1]
[1,] 0.1
[2,] 0.5
[3,] 0.7
result <- matrix(0, nrow = 150, ncol=1)
```

I need to create a vector of numbers (taken from e1) that repeat themselves depending on each number in 'block'

The code below demonstrates the desired outcome in this instance, however I'm trying to write a more flexible script that can cope with fewer than or more than 3 'blocks'

I appreciate there is probably a much easier way of doing this, but my head is stuck in loop mode and I can't seem to get out of it!

```
for (v1 in 1:days){
if(v1 <= block[1,1]){
result[v1,1] <- e1[1,1]
}
else if (v1 > block[1,1] & v1 <= block[2,1]){
result[v1,1] <- e1[2,1]
}
else if (v1 > block[2,1] & v1 <= block[3,1]){
result[v1,1] <- e1[3,1]
}
}
```

Any help would be much appreciated!

# Answer

1

Advertisement

You can get this by using a nice feature of `rep`

:

```
result <- rep(e1, c(block[1], diff(block)))
# cast the vector as a column matrix
result <- matrix(result, length(result))
```

This works because `rep`

will accept a vector in its second argument that tells it how many times to repeat each element of its first argument.

If you know the length ahead of time, you can combine the lines, like

```
result <- matrix(rep(e1, c(block[1], diff(block))), days)
```

for example.

Answer author Lmo

Advertisement

Tickanswer.com is providing the only single recommended solution of the question Populating a matrix using values from two other matrices of unpredictable size under the categories i.e r , loops , matrix , . Our team of experts filter the best solution for you.