You are here

Double Loop

I am working on a spatial analysis project, I need to evaluate a neighboring cells defined by a two dimensional matrix of numbers, so I have to find a smallest number around and move position to that cell, and then do the same operation for a new position. Normally I would do it using double loop which will search for a smallest number in dimension from i-1 to i+1 and j-1 to j+1 (i-horisontal and j-vertical) How can I implement this in a Similie?

Forums: 

OK. At the basic level, Simile gives you the functions least and posleast which you can apply to an array of values. The former returns the lowest value from the array, the latter the index of the lowest value.

Now, it seems you want the position of the lowest value from a 2-D array of values, call it [[var]]. Let's say the outer dimension represents rows of cells, and the inner dimension the individual cells within that row. First we need to find which row has the lowest value in it. To do this we make an array of the results of applying least() to each row of the original array, as follows:

[row_minima] = makearray(least(element([[var]], place_in(1))),size([[var]]))

we then get the position of the lowest value here:

row_index = posleast([row_minima])

This is the index of the row with the smallest value, and we can now find the column with that value

column_index = posleast(element([[var]], row_index))

It looks like you are only interested in values within one cell of your starting point, so you could make a 3x3-element array from your full matrix like this:

local = makearray(makearray(
element(element([[var]], place_in(2)+my_row-2),
place_in(1)+my_col-2), 3), 3)

though this might need some attention near the boundaries of the array unless you make it oversize.

If this is part of a more complex model you might wish to carry out the same task using an association submodel, but that is a separate topic. Hope these hints give you some ideas.

--Jasper