Page 1 of 1

loops to fill a matrix

Posted: Tue May 17, 2011 11:15 pm
by kuuks
Hi, I have another coding issue. I would like to fill a matrix using a for loop so that each cell in a column is equal to the value of the cell above it multiplied by (1 - the value of the cell above the corresponding cell in another matrix). Therefore, using microsoft excel to demonstrate, B2 = B1*(1-A1) and then dragging down. I've been using @subextract to extract just the one cell so it looks like this:

For !m=1 to @rows(x)
If !m>=2 then
x(!m)=(@subextract(x,!m-1,1,!m-1,1))*(@subextract(units,!m,1,!m,1)-(@subextract(y,!m-1,1,!m-1,1)))
endif
next

; where x is currently a vector and y is the other matrix (with the info) and units is a "ones" matrix. I figured I would nest this loop within another loop (if x was a nxn matrix instead) so that I can do the same procedure for every column. When I run the above code it tells me non-numeric argument in "x(2)=@subextract...."

Thanks heaps,
kuuks.

Re: loops to fill a matrix

Posted: Wed May 18, 2011 8:03 am
by EViews Gareth

Code: Select all

for !i=2 to @rows(x) x(!i, 1) = x(!i-1, 1)*(1-y(!i,1)) next
That will do it for the first col. You can then loop over the columns.

Re: loops to fill a matrix

Posted: Wed May 18, 2011 5:21 pm
by kuuks
Thanks Gareth that works very well. I just had to fill x with ones first, otherwise the vector fills with zeros. Regarding the greater loop, i turned x into a matrix and did as you said and every other column just filled with ones. The code is:

matrix x=@ones(101, 77)
For !n=1 to @columns(x)
For !m=2 to @rows(x)
x(!m,1)=x(!m-1,1)*(1-y(!m-1,1))
next
next

What am I missing?

Re: loops to fill a matrix

Posted: Wed May 18, 2011 5:27 pm
by kuuks
Ah I got it sorry. I forgot to put !n instead of 1 for the columns in the second loop:

matrix x=@ones(101, 77)
For !n=1 to @columns(x)
For !m=2 to @rows(x)
x(!m,!n)=x(!m-1,!n)*(1-deathprob_1yr(!m-1,!n))
next
next

Thanks again Gareth