Creating Matrices

Trying to build a matrix model.. Keep getting this error:
"Error in N.project[, 1] <- No :
number of items to replace is not a multiple of replacement length"

I have no idea how to fix this.
((((code below))))

n <- 4
A <- matrix(c(0,0,33.3,125.6,326.0,0.053,0,0,0,0,0,0.396,0,0,0,0,0,0.143,0,0,0,0,0,0.167,0,0,0,0,0,0),
  nrow=6,  byrow=TRUE)
# and the number of years, m, to be included in the projection 
t.proj <- 20
N.project <- matrix(0, nrow = nrow(A), ncol = t.proj + 1)
No <- c(4,3,2,1)
N.project[,1] <- No
for  (i in 1:t.proj) {
  N.project[,i + 1]  <- A %*% N.project[, i]
  }
matplot(t(N.project),log="y")

I changed N.project[,1] <- No

to I changed N.project[,0] <- No
and got no error!

I don't think

N.project[,0] <- No

does anything. I made a copy of N.project and executing your new line leaves the copy identical to the original.

N.project <- matrix(0, nrow = nrow(A), ncol = t.proj + 1)
No <- c(4,3,2,1)

N.project2 <- N.project
N.project2[,0] <- No
identical(N.project,N.project2)
[1] TRUE

N.project has six rows. You get the error because No only has four values. What are you trying to do?

1 Like

Trying to plot the matrix values, using matplot.
I have been getting the following error in reference to my original code^:

Error in A %*% N.project[, i] : non-conformable arguments

I am new to creating matrices in r so I am very inexperienced at this. Could you offer some advice?

I modified your code so that it does not throw errors but I DO NOT claim that this version does what you want. I only made the changes to illustrate where the problems are.

My version of No has six values.

No <- c(4,3,2,1,0,0)

It can then be assigned as the value of N.project[,1] because N.project has six rows.

I changed the line in the for loop to

N.project[,i + 1]  <- A %*% N.project[1:5, i]

A has five columns, so you cannot multiply it by N.project[, i] because N.project's six rows are not compatible with the five columns of A. By selecting only the first five rows on N.project, I avoid the error.

n <- 4
A <- matrix(c(0,0,33.3,125.6,326.0,0.053,0,0,0,0,0,0.396,0,0,0,0,0,0.143,0,0,0,0,0,0.167,0,0,0,0,0,0),
            nrow=6,  byrow=TRUE)
# and the number of years, m, to be included in the projection 
t.proj <- 20
N.project <- matrix(0, nrow = nrow(A), ncol = t.proj + 1)
No <- c(4,3,2,1,0,0)
N.project[,1] <- No
for  (i in 1:t.proj) {
  N.project[,i + 1]  <- A %*% N.project[1:5, i]
}
matplot(t(N.project),log="y")

Since I do not understand the purpose of multiplying A by columns in N.project to build a new N.project, I do not know how to really fix your code.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.