首页 > 解决方案 > 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]

标签: matlab

解决方案


干得好:

    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);

推荐阅读