John
John

Reputation: 3070

Reshape matrix with zeros padding

I am working with matrix using reshape function. I have a matrix size 990 x 8. First, I will reshape it to A x 400 where A will be determined s.t 990x8 is devisible by 400. So, we must add 80 zeros as padding. So, A is

 (990+10)/400=200

My new matrix is 20 x 400. Now I set one row as error row in A. Second step, I want to recovery my orignal matrix size 990 x 8 with that row error. So, the number row error will be

400/8=50 rows 

It is very clear when you see the below figure. Now I want to implement this scheme by matlab code. Let see my implementation as bellow. However, it does not similar my goal. It appeared some -1 in individual row (ex: [0 0 -1 0 0 ..], the true answer must be [0 0 0...] or [-1 -1 -1..] because if row without error will only constain 0 or 1, and error row is only -1 values). Please fix help me

    bitstream = reshape( orignalPacket.', [],1); %size 990 x 8
    %% Add padding        
    bitstream(end+80)=0; % add zeros padding at the end
    %% New matrix 20 x 400
    newmatrix= reshape( bitstream.', [],psize);
    %% Add one error row
    newmatrix(5,:)=-1; %row 5th is error

    %% Recovery to orignal packet
    bitstream_re = reshape( newmatrix, [],1);
    bitstream_re(end-80+1:end)=[];%% Remove padding
    matrix_re=reshape(permute(reshape(bitstream_re,size(bitstream_re,2),8,[]),[2 1 3]),8,[]);
    matrix_re=matrix_re'; %Recovery matrix- 

Upvotes: 1

Views: 2051

Answers (1)

Divakar
Divakar

Reputation: 221574

The problems you were encountering were because MATLAB uses column-major indexing and with your operations you were indexing into the matrices row-wise.

Here's the modified code that seems to work -

error_row = 5; %// row index to be set as error row

bitstream = orignalPacket; %// Assuming orignalPacket is of size 990 x 8

bitstream(end+10,:)=0; %// pad with 10 rows of zeros at the end

%// New matrix 20 x 400
newmatrix = reshape(bitstream.',400,20).';

%// Add one error row
newmatrix(error_row,:)=-1; %// row 5th is error

%// Recovery orignal packet
bitstream_re = reshape(newmatrix.',1,[]); %//'
bitstream_re(end-80+1:end)=[]; %// Remove padding

matrix_re = reshape(bitstream_re,8,[]).'; %//'# Recovered matrix

By the way, you can achieve the same output matrix_re without all these reshaping and tedious indexing with this -

matrix_re = orignalPacket; %// Assuming orignalPacket is of size 990 x 8
error_row = 5; %// row index to be set as error row
matrix_re(50*(error_row-1) + 1 :50*error_row,:) = -1;

Upvotes: 1

Related Questions