Matrix “Zigzag” Reordering

后端 未结 6 1512
名媛妹妹
名媛妹妹 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:04

    Here's a non-loop solution zig_zag.m. It looks ugly but it works!:

    function [M,index] = zig_zag(M)
      [r,c] = size(M);
      checker = rem(hankel(1:r,r-1+(1:c)),2);
      [rEven,cEven] = find(checker);
      [cOdd,rOdd] = find(~checker.'); %'#
      rTotal = [rEven; rOdd];
      cTotal = [cEven; cOdd];
      [junk,sortIndex] = sort(rTotal+cTotal);
      rSort = rTotal(sortIndex);
      cSort = cTotal(sortIndex);
      index = sub2ind([r c],rSort,cSort);
      M = M(index);
    end
    

    And a test matrix:

    >> M = [magic(4) zeros(4,1)];
    
    M =
    
        16     2     3    13     0
         5    11    10     8     0
         9     7     6    12     0
         4    14    15     1     0
    
    >> newM = zig_zag(M)    %# Zig-zag sampled elements
    
    newM =
    
        16
         2
         5
         9
        11
         3
        13
        10
         7
         4
        14
         6
         8
         0
         0
        12
        15
         1
         0
         0
    

提交回复
热议问题