Zigzag扫描代码 MATLAB版 支持M*N矩阵
即将一个 M * N 的矩阵,依 Zigzag 顺序扫描为 1 * (M*N) 的向量。
代码如下,仅供参考。
function [vec,vecNum] = zigzagScan(mtr)
% zigzagScan(img) Use zigzag pattern order to scan a matrix.
% [vec, vecNum] = zigzagScan(img) Scan a matrix by using zigzag
% pattern order. The input parameter matrix is a m-by-n matrix. The
% output parameter vec is a 1-by-(m*n) vector that generated by
% zigzag scan. The output parameter vecNum is the length of vector.
% In general, vecNum equals to (m*n).
%
% version: v1.0
% author: tianlan
% time: Dec 16, 2016
% CHECK INPUT ARGUMENTS
if nargin < 1
error('Not enough input arguments!');
elseif nargin > 1
error('Too many input arguments!');
end
% Get size of image.
[m,n,t] = size(mtr);
if t ~= 1
error('The input matrix needs to be m-by-n matrix!');
end
% SCAN A MATRIX BY USING ZIGZAG ORDER.
vec = mtr;
vec = reshape(vec,1,m*n);
% zigzag scan.
x = 1;
y = 1;
vecNum = 0;
vecNum = vecNum + 1;
vec(1,vecNum) = mtr(x,y);
while 1
% arrive right-up border, needs to change direction.
if (y+1) <= n && x == 1 %towards right one step.
y = y + 1;
elseif (y+1) > n && (x+1) <= m %towards down one step.
x = x + 1;
else
break;
end
vecNum = vecNum + 1;
vec(1,vecNum) = mtr(x,y);
%judge the scan process is arrived the right-down corner (i.e. mtr(m,n)) or not.
if x == m && y == n
break;
end
% scan the matrix towards with left-down direction.
while (y-1) >= 1 && (x+1) <= m
y = y - 1;
x = x + 1;
vecNum = vecNum + 1;
vec(1,vecNum) = mtr(x,y);
end
% arrive the left-down border, needs to change direction.
if (x+1) <= m && y == 1% towards down one step.
x = x + 1;
elseif (y+1) <= n && x == m %towards right one step.
y = y + 1;
else
break;
end
vecNum = vecNum + 1;
vec(1,vecNum) = mtr(x,y);
%judge the scan process is arrived the right-down corner (i.e. mtr(m,n)) or not.
if x == m && y == n
break;
end
% scan the matrix towards with right-up direction.
while (x-1) >= 1 && (y+1) <= n
x = x - 1;
y = y + 1;
vecNum = vecNum + 1;
vec(1,vecNum) = mtr(x,y);
end
end