Matlab-如何在矩阵中查找数字的相邻元素?

时间:2018-09-27 08:51:18

标签: matlab

例如,如果我有一个矩阵:

A=[1 2 3 4; 5 6 7 8; 9 10 11 12]

如果我选择数字6,那么它应该返回一个矩阵:

B=[1 2 3; 5 6 7; 9 10 11]

2 个答案:

答案 0 :(得分:0)

您在这里:

    A = [1 2 3 4; 5 6 7 8; 9 10 11 12];

    num=6;

    [i,j]=find(A==num);
    [len_row,len_col]=size(A);

    cols=(j-1):(j+1);
    cols(cols<1)=[]; %to avoid trying to access values outside matrix
    cols(cols>len_col); %to avoid trying to access values outside matrix

    row=(i-1):(i+1);
    row(row<1)=[]; %to avoid trying to access values outside matrix
    row(row>len_row)=[]; %to avoid trying to access values outside matrix

    new_mat=A(row,cols);

答案 1 :(得分:0)

将gutzcha的答案作为一个函数来实现,灵活性更高:

function mat_out = surround(mat_in, number, dis)
  %mat_in: input matrix containing number
  %number: number around which to build the output matrix
  %dis: distance around searched number to crop in_matrix
  %If dis is such that you would need to access values outside
  %matrix, you will end up getting a non square matrix.

  %find first position containing number in matrix:
  [i, j] = find(mat_in==number, 1); 

  [len_row, len_col] = size(mat_in);

  %make sure that I'm not accessing elements outside matrix
  col = max((j-dis), 1):min((j+dis), len_col);
  row = max((i-dis), 1):min((i+dis), len_col);

  mat_out =  mat_in(row, col);

然后得到您需要的东西,您就会做

B = surround(A, 6, 1)

以获得A中包含的3x3矩阵,其中心为6。通过此实现,您还可以使用变量dis获得具有相同特征的5x5矩阵(如果A较大)。为了避免冲突,我编写了它,以便您可以找到number的第一次出现,但是可以对其进行修改。

请注意,如果number距矩阵末尾的距离少于dis个数字,例如A中的数字2,则将得到最大的矩阵:

C = surround(A, 2, 1);

您将拥有

C = [1, 2, 3; 5, 6, 7]

您可以修改代码以使用零或任何其他数字填充,以便获得

C = [0, 0, 0; 1, 2, 3; 5, 6, 7]