簡體   English   中英

Matlab-如何在矩陣中查找數字的相鄰元素?

[英]Matlab- How to find the neighbouring elements of a number in a matrix?

例如,如果我有一個矩陣:

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

如果我選擇數字6,那么它應該返回一個矩陣:

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

干得好:

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

將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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM