buddy
buddy

Reputation: 41

zero padding a matrix

I have a 16X16 matrix. I have to add it to a 256X256 matrix. Can anyone help me how to make this 16X16 matrix into 256X256 filling the remaining with zeros?

Upvotes: 4

Views: 16324

Answers (5)

Mar Philip
Mar Philip

Reputation: 31

Use padarray function in Matlab. Use Help to know it's parameters

Upvotes: 3

SCFrench
SCFrench

Reputation: 8374

So, this doesn't actually answer your question, but I think it answers the use case you gave. Assuming you want to add the smaller matrix to the upper-left corner of the big matrix:

big = ones(256, 256);
small = ones(16, 16);
big(1:16, 1:16) = big(1:16, 1:16) + small;

This avoids allocating an extra 65000 or so doubles which you would have to do if you re-sized small from 16x16 to 256x256.

Upvotes: 3

groovingandi
groovingandi

Reputation: 2006

Matlab automatically pads with zeros if you assign something to an element outside of the original size.

>> A = rand(16, 16);
>> A(256, 256) = 0;
>> size(A)
ans =
   256   256

Upvotes: 10

zellus
zellus

Reputation: 9592

padded = zeros(256,256);
data = rand(16,16);
padded(1:16,1:16) = data;

Upvotes: 3

Bob Bryan
Bob Bryan

Reputation: 3837

First thing to do is create an output matrix that is 256x256, assuming you want to keep the original 256x256 matrix pristine. Next, move the values of the input 256x256 matrix into the output matrix. The next step is to add in the 16x16 elements to the output matrix.

But, before anyone can really answer this, you need to explain how the 16x16 matrix relates to the 256x256 matrix. In other words, is the first element (0,0) of the 16x16 matrix going to be added to the first element (0,0) of the 256x256 matrix? How about the secound element of (0, 1) - do you know where that is going to be added in? What about element (1, 0) of the 16x16 matrix - what element of the 256x256 matrix does that get added into? Once you figure this out, you should be able to simply code some loops to add in each element of the 16x16 matrix to the appropriate 256x256 output matrix element.

Upvotes: 0

Related Questions