Page 1 of 1
Searching a matrix for values "surrounding" it
Posted: Sun Sep 30, 2012 4:51 pm
by SudoCode
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.
Re: Searching a matrix for values "surrounding" it
Posted: Sun Sep 30, 2012 5:01 pm
by dreadkillz
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]
Re: Searching a matrix for values "surrounding" it
Posted: Sun Sep 30, 2012 5:47 pm
by SudoCode
Yes, index, not value, my mistake
Re: Searching a matrix for values "surrounding" it
Posted: Sun Sep 30, 2012 6:26 pm
by Inny
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