Matrix “Zigzag” Reordering

后端 未结 6 1556
名媛妹妹
名媛妹妹 2020-11-30 04:35

I have an NxM matrix in MATLAB that I would like to reorder in similar fashion to the way JPEG reorders its subblock pixels:

6条回答
  •  青春惊慌失措
    2020-11-30 05:14

    Consider the code:

    M = randi(100, [3 4]);                      %# input matrix
    
    ind = reshape(1:numel(M), size(M));         %# indices of elements
    ind = fliplr( spdiags( fliplr(ind) ) );     %# get the anti-diagonals
    ind(:,1:2:end) = flipud( ind(:,1:2:end) );  %# reverse order of odd columns
    ind(ind==0) = [];                           %# keep non-zero indices
    
    M(ind)                                      %# get elements in zigzag order
    

    An example with a 4x4 matrix:

    » M
    M =
        17    35    26    96
        12    59    51    55
        50    23    70    14
        96    76    90    15
    
    » M(ind)
    ans =
        17  35  12  50  59  26  96  51  23  96  76  70  55  14  90  15
    

    and an example with a non-square matrix:

    M =
        69     9    16   100
        75    23    83     8
        46    92    54    45
    ans =
        69     9    75    46    23    16   100    83    92    54     8    45
    

提交回复
热议问题