5

我想返回 3d 矩阵中一个单元格周围的 8 个单元格的索引和值。

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,:))

这适用于矩阵中心的值,但如果 pos 在边缘,它会中断。(例如,如果 pos 是[3,4,5],则around_pos 将包括[3,4,6],这是超出范围的)

显然我可以删除around_pos 值<0 或>size(mat),但这似乎不是一个非常好的MATLAB 方法。有任何想法吗?

4

3 回答 3

5

与此处讨论的解决方案相同,但扩展到多个(任何)维度:

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{:});

重要的部分是最后四行,它避免了每个维度的 c/p 最大值,最小值。

或者,如果您喜欢短代码,则循环更改为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{:});
于 2012-09-28T07:37:56.250 回答
4

这是一个整理后的版本。干杯。

mat = rand(5,5,5);
N = size(mat)
if length(N) < 3 || length(N) > 3; error('Input must be 3 dimensional'); end;
pos = [1 3 5]
surrounding_val = mat(max(pos(1)-1, 1):min(pos(1)+1, N(1)), max(pos(2)-1, 1):min(pos(2)+1, N(2)), max(pos(3)-1, 1):min(pos(3)+1, N(3))) 

编辑:添加了错误陷阱。

于 2012-09-28T07:10:41.333 回答
0

我发现这篇文章是因为我需要获取矩阵中选定点的周围索引。似乎这里的答案正在返回一个周围值的矩阵,但问题也对周围的索引感兴趣。我可以使用“try/catch”语句来做到这一点,我以前不知道 MATLAB 中存在这种语句。对于二维矩阵,Z:

%Select a node in the matrix
Current = Start_Node;

%Grab its x, y, values (these feel reversed for me...)
C_x = rem(Start_Node, length(Z));
if C_x ==0
    C_x =length(Z);
end
C_y = ceil(Start_Node/length(Z));
C_C = [C_x, C_y];

%Grab the node's surrounding nodes.
try
    TRY = Z(C_x - 1, C_y);
    Top = Current -1;
catch
    Top = Inf;
end
try
    TRY = Z(C_x + 1, C_y);
    Bottom = Current +1;
catch
    Bottom = Inf;
end
try
    TRY = Z(C_x, C_y + 1);
    Right = Current + length(Z);
catch
    Right = Inf;
end
try
    TRY = Z(C_x, C_y - 1);
    Left = Current - length(Z);
catch
    Left = Inf;
end

surround = [Top, Bottom, Left, Right];
m = numel(surround == inf);
k = 1;
%Eliminate infinites.

surround(surround==inf) =[];

我希望有人发现这些信息是相关的。

于 2013-09-27T14:54:10.010 回答