matlab - 3d 矩阵中周围单元格的索引和值

标签 matlab matrix

我想返回 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],surrounding_pos 将包括 [3,4,6],这是越界的)

我显然可以删除 surrounding_pos 值 <0 或 >size(mat),但这看起来不像是一个非常好的 MATLABian 方法。有任何想法吗?

最佳答案

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

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

关于matlab - 3d 矩阵中周围单元格的索引和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12635183/

相关文章:

python - python中Matlab的ranksum相当于什么?

c++ - 如何在 Eigen 中获取系数矩阵?

c - 将 MATLAB 与 C/C++ 程序连接起来

oop - 在 MATLAB 中覆盖父类(super class)方法和访问修饰符

arrays - 语言 |将函数作为参数传递给其他函数

matlab - 模拟来自联合累积分布函数的样本?

c++ - 在 C++ 中转置二维数组

c++ - 模板和矩阵转换

algorithm - 给定一个由 0 和 1 组成的 m x n 矩阵,如果一个元素为 0,则将其整个行和列设置为 0

图像与蒙版混合