I would like to return the indices and values of 8 cells surrounding a cell in a 3d matrix.
mat = rand(5,5,5);
% Cell of interest
pos = [3 3 3]
pos_val = mat(pos(1), pos(2), pos(3))
% Surrounding cells
surrounding_pos = [pos(1)-1:pos(1)+1; pos(2)-1:pos(2)+1; pos(2)-1:pos(2)+1]
surrounding_val = mat(surrounding_pos(1,:), surrounding_pos(2,:), surrounding_pos(3,:))
This works fine for values in the center of the matrix, but it breaks if pos is on the edge. (For example, if pos was [3,4,5], environment_pos will include [3,4,6]what goes beyond)
I could obviously remove the environment_pos <0 or> size (mat) values, but that doesn't look like the awful MATLABian method. Any ideas?
source
share