arrays - How do I compute the linear index of a 3D coordinate and vice versa? -
if have point (x, y z), how find linear index, point? numbering scheme (0,0,0) 0, (1, 0, 0) 1, . . ., (0, 1, 0) max-x-dimension, .... also, if have linear coordinate, i, how find (x, y, z)? can't seem find on google, results filled other irrelevant stuff. thank you!
there few ways map 3d coordinate single number. here's 1 way.
some function f(x,y,z) gives linear index of coordinate(x,y,z). has constants a,b,c,d want derive can write useful conversion function.
f(x,y,z) = a*x + b*y + c*z + d you've specified (0,0,0) maps 0. so:
f(0,0,0) = a*0 + b*0 + c*0 + d = 0 d = 0 f(x,y,z) = a*x + b*y + c*z that's d solved. you've specified (1,0,0) maps 1. so:
f(1,0,0) = a*1 + b*0 + c*0 = 1 = 1 f(x,y,z) = x + b*y + c*z that's solved. let's arbitrarily decide next highest number after (max_x, 0, 0) (0,1,0).
f(max_x, 0, 0) = max_x f(0, 1, 0) = 0 + b*1 + c*0 = max_x + 1 b = max_x + 1 f(x,y,z) = x + (max_x + 1)*y + c*z that's b solved. let's arbitrarily decide next highest number after (max_x, max_y, 0) (0,0,1).
f(max_x, max_y, 0) = max_x + max_y * (max_x + 1) f(0,0,1) = 0 + (max_x + 1) * 0 + c*1 = max_x + max_y * (max_x + 1) + 1 c = max_x + max_y * (max_x + 1) + 1 c = (max_x + 1) + max_y * (max_x + 1) c = (max_x + 1) * (max_y + 1) now know a, b, c, , d, can write function follows:
function linearindexfromcoordinate(x,y,z, max_x, max_y){ = 1 b = max_x + 1 c = (max_x + 1) * (max_y + 1) d = 0 return a*x + b*y + c*z + d } you can coordinate linear index similar logic. have marvelous demonstration of this, page small contain. i'll skip math lecture , give final method.
function coordinatefromlinearindex(idx, max_x, max_y){ x = idx % (max_x+1) idx /= (max_x+1) y = idx % (max_y+1) idx /= (max_y+1) z = idx return (x,y,z) }
Comments
Post a Comment