Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexes and values of surrounding cells in 3d matrix

Tags:

matrix

matlab

I'd like to return the indexes and values of the 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 centre of a matrix, but it breaks if pos is on the edge. (E.g. if pos was [3,4,5], surrounding_pos would include [3,4,6], which is out of bounds)

I could obviously remove surrounding_pos values <0 or >size(mat), but this doesn't seem like a terribly MATLABian method. Any ideas?

like image 883
Alex L Avatar asked Sep 28 '12 07:09

Alex L


People also ask

What does a 3D matrix represent?

3-D Matrix is a multidimensional array that is an extension of two-dimensional matrices. As you can guess, they will have 3 subscripts, one subscript along with row and column indexes as for the 2D matrix. The third subscript in a 3D Matrix is used to represent the sheets or pages of an element.

How do you represent a 3 dimensional matrix?

Three-dimensional matrices can be created using the zeros, ones, and rand functions by specifying three dimensions to begin with. For example, zeros(2,4,3) will create a 2 × 4 × 3 matrix of all 0s. Here is another example of creating a three-dimensional matrix.

Can you have 3D matrices?

Yes, these exist. "3D array" would be a common, essentially unambiguous way to refer to this in computer science.


1 Answers

Same solution as discussed here, but extended to multiple (any) dimensions:

mat = randi(10,5,5,5);
siz = size(mat );
N = numel(siz); % number of dimensions
M = 1; % surrounding region size

pos = [3 3 3];
pos_val = mat(pos(1), pos(2), pos(3));

surrounding_pos = cell(N,1);
for ii=1:N
    surrounding_pos{ii} = max(1,pos(ii)-M):min(siz(ii),pos(ii)+M);
end
surrounding_val2 = mat(surrounding_pos{:});

The important part is the last four lines, it avoids having to c/p the max, min thing for every dimension..

Or if you like short code, the loop changed to an arrayfun:

surrounding_pos = arrayfun(@(ii) max(1,pos(ii)-M):min(siz(ii),pos(ii)+M), 1:N,'uni',false);
surrounding_val2 = mat(surrounding_pos{:});
like image 82
Gunther Struyf Avatar answered Oct 27 '22 17:10

Gunther Struyf