Re: [R] Matrix indexing in a loop

From: Pontarelli, Brett <bpontar_at_amazon.com>
Date: Sat 18 Feb 2006 - 10:04:18 EST


Do you have to use a loop? The following function should do what you want for the 1st order:

rook = function(Y) {

	rsub = function(Z) {
		X = matrix(0,nrow(Z),ncol(Z));
		X[1:(N-1),1:M] = X[1:(N-1),1:M] + Z[2:N,1:M];
		X[2:N,1:M] = X[2:N,1:M] + Z[1:(N-1),1:M];
		X[1:N,1:(M-1)] = X[1:N,1:(M-1)] + Z[1:N,2:M];
		X[1:N,2:M] = X[1:N,2:M] + Z[1:N,1:(M-1)];
		return(X);
	}
	return(rsub(Y)/rsub(matrix(1,nrow(Y),ncol(Y))));
}

I'm not sure I understand how the higher orders work. For example, an interior element for the 1st order is always divided by 4. Is an interior element for a 3rd order divided by 4 or 8 or something else? Also, how are you implementing your 3D matrices?

--Brett

-----Original Message-----
From: r-help-bounces@stat.math.ethz.ch [mailto:r-help-bounces@stat.math.ethz.ch] On Behalf Of Mills, Jason Sent: Friday, February 17, 2006 1:36 PM
To: r-help@stat.math.ethz.ch
Subject: [R] Matrix indexing in a loop

How do you specify matrix location a[i,j] (or a[i-1,j], etc.) in a "for" loop?

I am looking for a flexible method of indexing neighbors over a series of lags (1,2,3...) and I may wish to extend this method to 3D arrays.

Example:

Data matrix
> fun

     [,1] [,2] [,3]

[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12


For each element a[i,j] in "fun", sum the 1st order (Rook's) neighbors:

a[i-1,j]

a[i+1,j]

a[i,j-1]

a[i,j+1]

Then divide by the number of elements included as neighbors-- this number depends on the location of a[i,j] in the matrix.

Insert the product of the neighbor calculation for each a[i,j] into the corresponding position b[i,j] in an empty matrix with the same dimensions as "fun".

For example, element [2,2] in "fun" should yield element [2,2] in a new matrix equal to 24/4=6. Of course, element [1,1] in the new matrix should be the product of only two numbers.

Thanks

J. Mills

        [[alternative HTML version deleted]]



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sat Feb 18 10:09:50 2006

This archive was generated by hypermail 2.1.8 : Mon 20 Feb 2006 - 14:08:40 EST