From help-request at octave dot org Thu Feb 10 06:01:04 2005 Subject: Re: Access the neighbors of an element From: Francesco Potorti` To: Joerg Sommer CC: help at octave dot org Date: Thu, 10 Feb 2005 13:03:37 +0100 >I want to compare the neighbors of an element to the element, but this is >harder than I thought. > >My idea: > > neighbor = [-n, n, -1, 1] + pos(t); > if any(neighbor(4) == down) > neighbor(4) = []; > end > if any(neighbor(3) == up) > neighbor(3) = []; > end > if neighbor(2) > n*n > neighbor(2) = []; > end > if neighbor(1) < 1 > neighbor(1) = []; > end > Y_energ = X_energ + 2*(length(neighbor) -... > 2*sum( X(pos(t)) ~= X(neighbor) )); > >But this is slower than > Y_energ = 2* (n*(n-1)... > - sum(sum( Y(1:n-1, :) == Y(2:n, :) ))... > - sum(sum( Y(:, 1:n-1) == Y(:, 2:n) )) ); > >with n=20. In one sentence: it is faster to compare and count twice >nearly 800 elements, than find and access the four neighbors of an >element. That's lunatic. sum is a very quick operation, while evaluating an if is not, and you do it four times. Generally speaking, builtin functions are very quick, as long as your data fit in real memory, while interpreting code is not. >How can I make it better? I am not sure I understand what you want to do. -- Francesco Potort́ (ricercatore) Voice: +39 050 315 3058 (op.2111) ISTI - Area della ricerca CNR Fax: +39 050 313 8091 via G. Moruzzi 1, I-56124 Pisa Email: Potorti at isti dot cnr dot it Web: http://fly.isti.cnr.it/ Key: fly.isti.cnr.it/public.key ------------------------------------------------------------- Octave is freely available under the terms of the GNU GPL. Octave's home on the web: http://www.octave.org How to fund new projects: http://www.octave.org/funding.html Subscription information: http://www.octave.org/archive.html -------------------------------------------------------------