You are currently viewing Matlab code to read Matrix in a ZigZag Scanning Method

Matlab code to read Matrix in a ZigZag Scanning Method

Spread the love

The zig-zag scanning pattern for run-length coding of the quantized DCT coefficients was established in the original MPEG standard. The same pattern is used for luminance and for chrominance. A modified (alternate) pattern more suitable for coding of some interlaced picture blocks was added in the MPEG-2 standard. A bit in the picture layer header, if set, selects the alternate scan.

Sample Program Created using the below functions

a=[1 2 3 4; 5 6 7 8 ;9 10 11 12; 13 14 15 16];
disp(a);
b=toZigzag(a);
disp(b);
c=invZigzag(b);
disp(c);

Function to read the square matrix in ZigZag Scanning

function y=toZigzag(x)
% transform a matrix to the zigzag format

%x=reshape(1:16,[4 4])';

[row col]=size(x);

if row~=col
disp('toZigzag() fails!! Must be a square matrix!!');
return;
end;

y=zeros(row*col,1);
count=1;
for s=1:row
if mod(s,2)==0
for m=s:-1:1
y(count)=x(m,s+1-m);
count=count+1;
end;
else
for m=1:s
y(count)=x(m,s+1-m);
count=count+1;
end;
end;
end;

if mod(row,2)==0
flip=1;
else
flip=0;
end;

for s=row+1:2*row-1
if mod(flip,2)==0
for m=row:-1:s+1-row
y(count)=x(m,s+1-m);
count=count+1;
end;
else
for m=row:-1:s+1-row
y(count)=x(s+1-m,m);
count=count+1;
end;
end;
flip=flip+1;
end;

Matlab code to Convert  array to matrix in inverse zigzag method

function y=invZigzag(x)
% inverse transform from the zigzag format to the matrix form

row=round(sqrt(length(x)));

if row*row~=length(x)
disp('invZigzag() fails!! Must be a square matrix!!');
return;
end;

y=zeros(row,row);
count=1;
for s=1:row
if mod(s,2)==0
for m=s:-1:1
y(m,s+1-m)=x(count);
count=count+1;
end;
else
for m=1:s
y(m,s+1-m)=x(count);
count=count+1;
end;
end;
end;

if mod(row,2)==0
flip=1;
else
flip=0;
end;

for s=row+1:2*row-1
if mod(flip,2)==0
for m=row:-1:s+1-row
y(m,s+1-m)=x(count);
count=count+1;
end;
else
for m=row:-1:s+1-row
y(s+1-m,m)=x(count);
count=count+1;
end;
end;
flip=flip+1;
end;