Search code examples
matlabmatrix-indexing

Matlab: Copy a diamond portion of an array


Suppose the array is:

A =    a b c
       d e f
       g h i

I want to copy the diamond arrangement, i.e. the elements d,b,f,h,e into a new 1D array. The above array is just an example, the matrix could be any size rectangular matrix and the location of the diamond can be anywhere within the array.


Solution

  • This works by building a mask (logical index) with the desired diamond shape and a specified center. The mask is obtained by computing the L1 (or taxicab) distance from each entry to the diamond center and comparing to the appropriate threshold:

    A = rand(7,9); %// example matrix
    pos_row = 3; %// row index of diamond center
    pos_col = 5; %// col index of diamond center
    [n_rows, n_cols] = size(A);
    d = min([pos_row-1 pos_col-1 n_rows-pos_row n_cols-pos_col]); %// distance threshold 
        %// to be used for mask. Obtained by extending until some matrix border is found
    ind = bsxfun(@plus, abs((1:n_rows).'-pos_row), abs((1:n_cols)-pos_col))<=d; %'// mask
    result = A(ind); %// get entries defined by mask