## Searching a matrix for values "surrounding" it

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
SudoCode
Citizen
Posts: 61
Joined: Fri May 04, 2012 7:05 pm

### Searching a matrix for values "surrounding" it

So I have a 100x100 matrix, created by

Code: Select all

function newNodeMap(tableName, numRows, numColumns)
for i = 1, numRows do
tableName[i] = {}
for j = 1, numColumns do
tableName[i][j] = 0
end
end
end

Which is then populated with values from 0-2 by tile properties from Advanced Tiled Loader. The problem now is that I need a way to read specific values of the matrix if given one index. i.e. [i+1], [i-1]. [j+1], [j-1], [i+1][j-1], etc.

I googled a bit but essentially everything I found was for matlab and I'm not familiar with the syntax.
Last edited by SudoCode on Sun Sep 30, 2012 5:48 pm, edited 1 time in total.

Party member
Posts: 223
Joined: Sun Mar 04, 2012 2:04 pm
Location: USA

### Re: Searching a matrix for values "surrounding" it

Could you rephrase your question? Do you mean you want to get the surrounding 8 values in a matrix if you're given an index?

Kinda like this?

[x][x][x]
[x][x]
[x][x][x]

SudoCode
Citizen
Posts: 61
Joined: Fri May 04, 2012 7:05 pm

### Re: Searching a matrix for values "surrounding" it

Yes, index, not value, my mistake

Inny
Party member
Posts: 652
Joined: Fri Jan 30, 2009 3:41 am
Location: New York

### Re: Searching a matrix for values "surrounding" it

I'm going to interpret this as you've given a location, say (50, 50) and need to check (49, 49) through (51, 51) for something. This is easily done with a few pieces of code:

Use this function to safely get values from the matrix:

Code: Select all

function getFromNodeMap(tableName, row, column)
local row = tableName[row]
if type(row)=="nil" then return 0 end -- Or some terminal value that's acceptable
local value = tableName[column]
if type(value)=="nil" then return 0 end -- Or some terminal value that's acceptable
return value
end

Now, it's safe to pull the 8 surrounding values:

Code: Select all

function getValuesAround(tableName, row, column)
local values = {}
for y = row-1, row+1 do
for x = column-1, column+1 do
if y~=row and x~=column then
values[#values+1] = getFromNodeMap(tableName, y, x)
end
end
end
return values
end


### Who is online

Users browsing this forum: No registered users and 37 guests